pstorage
English | 简体中文
What is pstorage ?
It's a common storage manager. It can adapt to kinds of storage, and manage the stored data reasonably.
Why we need it ?
- Support multi-end storage adaptation
- Unified storage data management
- Runtime caching to reduce read pressure on Storage
- Master the information of the stored data
- Simultaneous support for synchronous and asynchronous writing
- Compatible with other apis that are not used by the storage
Usage
Before we use it, we should init it in entry file and set as a global variable:
const Storage = ;const storage = target: localStorage keys: 'userInfo';// set it as a global variable// Like browerwindowstorage = storage;// Like weixin miniprogram, in app.js;
Store storage item:
const storage = windowstorage;const userInfo = name: 'Jack';/** * UserInfo is stored in runtime as: * { * value: { * name: 'Jack' * } * } * Persistent store is: * '{"value": "{"name":"Jack"}"}' */// Store sync, return undefinedtry storage; catch err console;// Store async, and return a promisestorage ;
Get storage item:
const storage = windowstorage;// Sync methodtry const userInfo = storage; catch err console;// Async methodstorage;
Remove storage item:
const storage = windowstorage;// Sync methodtry storage; catch err console;// Async methodstorage;
Clear all items
const storage = windowstorage;// Sync methodtry storage; catch err console;// Async methodstorageclear'userInfo';
Get current storage information
const storage = windowstorage;// Sync methodtry const result = storage; catch err console;// Async methodstorage;
Property | Type | Description |
---|---|---|
keys | Array. | All keys currently stored |
currentSize | number | The amount of space currently occupied, in KB |
limitSize | number | Limit space size in KB |
Notice
Due to differences between containers, only miniprogram app platforms return a valid limitSize
.
Use storage adapter
Storage adapter's target is override storage's native method, and all configurations are optional.
const Storage = ; const getItemAsync = { return { try const value = ; ; catch err ; };};const setItemAsync = { return { try ; ; catch err ; };}; const storage = target: localStorage keys: 'userInfo' adapters: getItem: setItem: getItemSync: localStoragegetItem setItemSync: localStoragesetItem ;
The official storage already supported in the web container are: localStorage
, sessionStorage
;
Supported in the miniprogram container: weChat miniprogram, ali miniprogram, toutiao miniprogram;
Supported in the React-Native container: AsyncStorage
Compatible with other apis that are not used by the storage
Just like React-Native:
;; const storage = target: AsyncStorage keys: 'userInfo'; storage;