Feature-enhanced wrappers for the Web Storage interface
- transparent (de)serialization
- transparent Base64 decoding (optional)
- Object-level read & write access
- batch operations
- support for events
- async transaction option (through IndexedDB)
npm install web-porridge -S
All methods and properties of the Web Storage API have equivalents on localPorridge
/ sessionPorridge
, completed by additional methods for batch operations.
import { localPorridge, sessionPorridge } from 'web-porridge';
// Optionally, use it as drop-in replacement
window['localStorage'] = localPorridge;
window['sessionStorage'] = sessionPorridge;
Alternatively, you can import the class and instantiate with custom defaults, e.g. to globally enable Base64 decoding or to disable JSON decoding.
import { WebPorridge } from 'web-porridge';
const localPorridge = new WebPorridge('localStorage', {
decodeBase64: true,
decodeJSON: false
});
Note: The Base64-decoding feature has primarily been added with Amazon Cognito JSON Web Tokens in mind, but since it is impossible to tell apart text strings from Base64 encoded strings, it is now disabled by default. This behaviour can toggled globally (as seen in the example above) or in the method call options.
It's recommended to import the library in your code, but you can also use the dist
-files or load them from a CDN.
Example
<script src="https://cdn.jsdelivr.net/npm/web-porridge@latest/dist/porridge.js"></script>
<script>
const localPorridge = new WebPorridge('localStorage');
const sessionPorridge = new WebPorridge('sessionStorage');
</script>
Usage: getItem(key, dot.notation.subkey? = '', options = {})
Returns the value of a single storage key, automatically parses JSON strings and, optionally, decodes Base64. Supports returning only the value inside an object through the use of dot notation syntax.
Example
localPorridge.getItem('firstItem');
localPorridge.getItem('secondItem', 'dot.notation.subkey');
The boolean options decodeBase64
and decodeJSON
can be used to toggle decoding of the respective values.
Usage: getItems([...], options = {})
Returns value of many storage keys, automatically parses JSON strings and, optionally, decodes Base64. Supports returning only the value inside an object through the use of dot notation syntax.
Example
localPorridge.getItem([
// String!
'firstItem',
{
// Object!
key: 'secondItem',
subKey: 'dot.notation.subkey'
},
[
// Array!
'thirdItem',
'dot.notation.subkey'
]
]);
The boolean options decodeBase64
and decodeJSON
can be used to toggle decoding of the respective values.
Usage: setItem(key, value, dot.notation.subkey? = '')
Writes a single key/value pair to the storage, automatically stringifies objects. Supports overwriting a single value inside an object through the use of dot notation syntax.
Example
localPorridge.setItem('firstItem', 'Hello World');
localPorridge.setItem('secondItem', { name: 'John Appleseed' });
localPorridge.setItem('secondItem', 'Ada Lovelace', 'name');
Usage: setItems([...])
Writes many key/value pairs to the storage, automatically stringifies objects. Supports overwriting a single value inside an object through the use of dot notation syntax.
Example
localPorridge.setItems([
{
// Object!
key: 'firstItem',
value: 'Hello World!'
},
{
// Another Object!
key: 'secondItem',
value: 'Appleseed',
subKey: 'personal.lastName'
},
[
// Array!
'thirdItem',
'Lovelace',
'personal.lastName'
]
]);
Usage: removeItem(key, dot.notation.subkey? = '')
Deletes a single storage key or object key through the use of dot notation syntax.
Example
localPorridge.removeItem('firstItem');
localPorridge.removeItem('secondItem', 'dot.notation.subkey');
Usage: removeItems([...])
Deletes storage keys or object keys through the use of dot notation syntax.
Example
localPorridge.removeItems([
// String!
'firstItem',
{
// Object!
key: 'secondItem',
subKey: 'dot.notation.subkey'
},
[
// Array!
'thirdItem',
'dot.notation.subkey'
]
]);
The
clear()
method of theStorage
interface clears all keys stored in a givenStorage
object.– MDN
The
key()
method of theStorage
interface, when passed a number n, returns the name of the nth key in a givenStorage
object. The order of keys is user-agent defined, so you should not rely on it.– MDN
The
length
read-only property of theStorage
interface returns the number of data items stored in a givenStorage
object.– MDN
The library provides methods to setup event listeners and dispatch WebPorridge actions. These actions are name after the WebPorridge methods.
Example
import { localPorridge } from 'web-porridge';
// Initialize event listeners
localPorridge.listen();
// Dispatch event
localPorridge.dispatch(
'setItem', {
key: 'demo',
value: 'Hello World!'
}
);
// Remove event listeners
localPorridge.mute();
Usage: listen(element: Element)
Adds an event listener for WebPorridge actions
Usage: mute(element: Element)
Removes an event listener
Usage: dispatch(action: string, payload: any)
You can use the same interface to write key/value pairs to IndexedDB instead of Web Storage. This allows for asynchronous transactions while using the more familiar API.
Note: All methods and properties provided by the WebPorridge API are supported!
import { db } from 'web-porridge';
(async () => {
const inputValue = 'Hello World!';
await db.setItem('demo', inputValue);
const outputValue = await db.getItem('demo');
console.log(inputValue === outputValue);
// true
db.clear();
})();
Again, you can instantiate the class yourself to override its defaults.
import { WebPorridgeDB } from 'web-porridge';
const db = new WebPorridgeDB({
databaseName: 'Custom DB',
decodeBase64: true,
decodeJSON: false,
storeName: 'Custom Store'
});
When IndexedDB is supported by the browser, you can use this interface as drop-in replacement for Web Storage, including sessionStorage
.
Example
import { db } from 'web-porridge';
window['sessionStorage'] = db;
window.addEventListener('beforeunload', () => sessionStorage.clear());
It's recommended to import the library in your code, but you can also use the dist
-files or load them from a CDN.
Example
<script src="https://cdn.jsdelivr.net/npm/web-porridge@latest/dist/porridge-db.js"></script>
<script>
const db = new WebPorridgeDB();
</script>
This module exposes its two helper function to encode and decode Base64:
Example
import { sessionPorridge, base64Encode, base64Decode } from 'web-porridge';
sessionPorridge.setItem('demo', base64Encode('Hello World!'));
const decodedStorage = base64Decode(sessionStorage.getItem('demo'));
const decodedPorridge = sessionPorridge.getItem('demo', { decodeBase64: true });
console.log(decodedPorridge === decodedStorage);
// true
This work is licensed under The MIT License
You are welcome to support this project using Flattr or Bitcoin 17CXJuPsmhuTzFV2k4RKYwpEHVjskJktRd