2.1.0 • Published 5 years ago

storagex v2.1.0

Weekly downloads
4
License
MIT
Repository
github
Last release
5 years ago

StorageX

A data storage scaffold which helps developer to use localStorage/sessionStorage/Storage or any other storage easliy.

Install

npm i storagex

Usage

ES6:

import StorageX from 'storagex'

CommonJS:

const { StorageX } = require('storagex')

Normal Browsers:

<script src="./node_modules/storagex/dist/storagex.js"></script>
<script>
const { StorageX } = window['storagex']
</script>

To use:

const store = new StorageX(options)
store.set('my_key', { value: 'ok' })

const value = store.get('my_key') // { value: 'ok' }

Options

const options = {
  namespace: string,
  expire: number,
  storage: Storage,
  stringify: boolean,
  async: boolean,
}

namespace

String to be prepended to each key. This distinguish different group of values. It is recommended to use '.' like 'com.docker.service.data'.

Notice: two StorageX instances should not have same namespace. If they have same namespace, the value in storage will be override by each other.

expire

How long the value will be expired. Unit is ms. If you set '0', it means the value will never expire.

storage

Which storage driver do you want to use: localStorage, sessionStorage, AsyncStorage or any other Storage API (getItem, setItem, removeItem).

AsyncStorage is used for react-native, when you pass AsyncStorage, options.async should MUST be true. inDB is a library to use indexedDB as storage, you can use its key-value mode and with options.async=true to use it too.

stringify

Whether to use JSON.stringify to stringify data before put into storage. Default is true.

This is based on what real storage you are using. For example, when you use localStorage/sessionStorage, you SHOULD MUST NOT set stringify to be false, because they do not support store no-string values.

async

Whether to use async mode. When true, all methods will return a promise, so that you can use async functions easliy:

const store = new StorageX({
  async: true,
})

;(async function() {
  const value = await store.get('my_key')
})()

This is based on what real storage you are using. For example, when you use AsyncStorage/inDB(kv mode), you SHOULD MUST set async to be true, becuase they do not support sync mode.

Methods

set(key, value, expire?)

Add a data to the storage. key is a string, which will be connected with 'namespace'. value can be any data type, such as object, Date and so on.

store.set('the_key', 'value')

If expire is not set, options.expire will be used.

get(key)

Get data from storage by key. If no data found by the key, or the data is expired, undefined will be returned.

remove(key)

Remove a certain data from the storage by key.

clear()

Clear the whole store data.

keys()

Return all keys of this namespace.

all()

Return all records in storage.