@yr/local-storage
v3.1.0
Published
A localStorage wrapper
Downloads
1
Readme
An localStorage
wrapper. Works in environments without localStorage
(Node.js, for example), or in those with restricted access (some browser prevent access during private browsing, for example).
Usage
const localStorage = require('@yr/local-storage');
localStorage.init({
maxKeyLength: 2,
version: { foo: 1, bar: 2 },
writeDelay: 100
});
localStorage.set('foo/bar', { boo: false });
localStorage.get('foo'); //=> { bar: { boo: false } }
localStorage.remove('foo');
API
init(options): override defaults. Options include:
- maxKeyLength: Number: the number of key segments to store data under (default
3
) - version: Object: an object specifying schema versions for a given set of keys. If
version
has previously been set, any version differences will be flagged and accessible via theshouldUpgrade
method - writeDelay: Number: the delay in ms to use for batching and flushing writes to disk/memory (default
1000
)
set(key, value): store value
at key
. Calls to set()
are batched and flushed to disk/memory (based on options.writeDelay
set in init()
)
localStorage.set('foo/bar', 'bar');
localStorage.set('foo/boo', { boo: true });
get(key): retrieve an object of all items matching key
localStorage.get('foo'); //=> { 'bar': 'bar', 'boo': { boo: true } }
localStorage.get(); //=> { foo: { 'bar': 'bar', 'boo': { boo: true } }
localStorage.get('bar'); //=> undefined
remove(key): remove item at key
localStorage.remove('foo/bar');
localStorage.get('foo/bar'); //=> undefined
flush(): write all pending changes to disk/memory
clear(): remove all items (preserves version
data)
destroy(): remove all items and reset to defaults
shouldUpgrade(namespace): determine if versioned namespace
should be upgraded based on version mismatch (from options.version
set in init()
)
localStorage.init({ version: { foo: 2, bar: 2 }});
localStorage.shouldUpgrade('foo'); //=> true
localStorage.shouldUpgrade('bar'); //=> false