GithubHelp home page GithubHelp logo

pax-k / rn-async-storage-level Goto Github PK

View Code? Open in Web Editor NEW
3.0 2.0 1.0 45.81 MB

⚡️ An abstract-level implementation of AsyncStorage for React Native using TypeScript

Shell 2.91% TypeScript 50.02% Java 25.33% JavaScript 1.63% Ruby 10.35% Objective-C 0.92% Objective-C++ 8.52% Swift 0.32%
abstract-level async-storage expo level react-native typescript rn-async-storage-level

rn-async-storage-level's Introduction

⚡️ RNAsyncStorageLevel

This is an abstract-level implementation of AsyncStorage for React Native using TypeScript.

It was tested with Expo SDK 48 for iOS & Android.

❗️❗️❗️ Moved to @hyphen-id/rn-async-storage-level ❗️❗️❗️

🔥 Prerequisites

AsyncStorage has to be installed, and development builds have to be created:

yarn add @react-native-async-storage/async-storage
yarn expo run:ios
yarn expo run:android

💿 Installation

yarn add @pax-k/rn-async-storage-level

🏋️ Usage

✅ With promises (prefered way)

import { RNAsyncStorageLevel } from '@pax-k/rn-async-storage-level'
import AsyncStorage from '@react-native-async-storage/async-storage'

async function withAsync() {
  try {
    // create a new db
    const db = new RNAsyncStorageLevel(AsyncStorage, 'my-db-1')

    // listen for 'put' events
    db.on('put', (key, value) => {
      console.log('event: put', key, value)
    })

    // listen for 'del' events
    db.on('del', (key) => {
      console.log('event: del', key)
    })

    // listen for 'clear' events
    db.on('clear', () => {
      console.log('event: clear')
    })

    // write some data
    await db.put('key1', 'value1')
    await db.put('key2', 'value2')

    // get the value of one key
    console.log(await db.get('key1'))

    // get the values of multiple keys
    console.log(await db.getMany(['key1', 'key2']))

    // get all keys
    console.log(await db.keys().all())

    // get all values
    console.log(await db.values().all())

    // get all entries
    console.log(await db.iterator().all())

    // delete a key
    await db.del('key1')

    // clear db
    await db.clear()
  } catch (error) {
    console.error(error)
  }
}

🌝 With callbacks (prefer promises)

import { RNAsyncStorageLevel } from '@pax-k/rn-async-storage-level'
import AsyncStorage from '@react-native-async-storage/async-storage'

async function withCallbacks() {
  // create a new db
  const db = new RNAsyncStorageLevel(AsyncStorage, 'my-db-1')

  // listen for 'put' events
  db.on('put', (key, value) => {
    console.log('event: put', key, value)
  })

  // listen for 'del' events
  db.on('del', (key) => {
    console.log('event: del', key)
  })

  // listen for 'clear' events
  db.on('clear', () => {
    console.log('event: clear')
  })

  // write some data
  db.put('key1', 'value1', (err) => {
    if (err) console.error(err)
    console.log('put callback')
  })

  db.put('key2', 'value2', (err) => {
    if (err) console.error(err)
    console.log('put callback')
  })

  // get the value of one key
  db.get('key1', (err, result) => {
    if (err) console.error(err)
    console.log('get callback', result)
  })

  // get the values of multiple keys
  db.getMany(['key1', 'key2'], (err, result) => {
    if (err) console.error(err)
    console.log('getMany callback', result)
  })

  // get all keys
  db.keys().all((err, result) => {
    if (err) console.error(err)
    console.log('keys callback', result)
  })

  // get all values
  db.values().all((err, result) => {
    if (err) console.error(err)
    console.log('values callback', result)
  })

  // get all entries
  db.iterator().all((err, result) => {
    if (err) console.error(err)
    console.log('iterator callback', result)
  })

  // delete a key
  db.del('key1', (err) => {
    if (err) console.error(err)
    console.log('del callback')
  })

  // clear db
  db.clear((err) => {
    if (err) console.error(err)
    console.log('clear callback')
  })
}

🙋‍♂️ FAQ

👉🏻 Why build this

There was no modern and actively maintained abstract-level compatible storage for React Native.

👉🏻 Why this works

abstract-level uses NodeJS native functions which won't work in a browser (or in the Hermes JS engine for React Native). At build time, parcel pollyfills some of the native functions, but misses text-encoding. This is injected by build.sh, then browserify bundles everything together into a 100% browser compatible module.

Apart from bundling, it is important to have AsyncStorage module installed in the consumer app, for it to referece the correct bindings. This is why it needs to be refereced from the app:

const db = new RNAsyncStorageLevel(AsyncStorage, 'my-db-1')

🚧 Limitations

  • Known storage limits
  • a value's type is limited to string | number | boolean | null | undefined
  • no support for snapshots, keyIterator, valueIterator, iteratorNextv, streams, seek, batch
  • without support for snapshots, isolation of transactions is instead guaranteed by using await/promises (as they are sequential), as opposed to callbacks that use queueMicrotask

👷 TODO

  • support for keyIterator, valueIterator, iteratorNextv, batch operations
  • support for Uint8Array as value type (for storing files as blobs)
  • caching + invalidation
  • add tests

🌈 Shouts 👏🏻

To Hyphen for sponsoring this effort and to TBD for powering the next wave of private & decentralised apps.

👋 Contribute

Running the project locally

git clone https://github.com/pax-k/rn-async-storage-level && cd rn-async-storage-level
yarn
cd expo-demo && yarn && yarn expo start:ios
cd ../ && yarn watch

rn-async-storage-level's People

Contributors

pax-k avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

mykin-ai

rn-async-storage-level's Issues

Polyfills should be set in the user's project not in this package

Based on the conversation I saw in Discord I just wanted to call out that this repo shouldn't set any polyfills like btoa/atob, textencoder, and so on for the user of the package. It's fine to use those inside the example project, but they should not be set in the code of the package. For example you're providing buffer in dist/main.js but you should actually be relying on the user's global.buffer (or lack thereof, and then throw).

Polyfills can be handled as a matter of documentation, for example forewarning the user that they will need those polyfills and providing example code for how to use the polyfills.

In our react native projects at TBD we're using react-native-quick-crypto , react-native-quick-base64,fastestsmallesttextencoder, react-native-bignumber, @craftzdog/react-native-buffer, and stream-browserify. We are avoiding browserify packages in general, and JS based polyfills where possible. A native C++ implementation seems lacking for streams and text encoding in the community, which we hope can be addressed by us or the community at a later point.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.