Persistence
A wrapper for persisting data to localStorage
or sessionStorage
.
You can create multiple instances but you must provide unique names;
The API resembles the one from the web storage objects: setItem(key, vaue)
, getItem(key)
, removeItem(key)
, but there are also shorter aliases: set()
, get()
and remove()
.
In order to avoid expensive JSON serialization/deserialization by interacting with the storage backend, the data is held in memory (in a simple object).
All operations operate on that plain object. An event listener is registered for the window.beforeunload
event, and only then we will serialize the data to an actual JSON string.
The string is then persisted to the backend storage, e.g. window.localStorage
(default).
Example:
const storage = new Persistence('storage');
storage.setItem('started', new Date());
console.log(storage.getItem('started'));
Static Member Summary
Static Public Members | ||
public static get |
An array containing all instances. |
|
public static |
Whether to log details to the console when certain static methods are called. |
Static Method Summary
Static Public Methods | ||
public static |
Clears the data of all instances. |
|
public static |
Returns an already existing instance for a given name or creates a new instance and returns it. |
|
public static |
Filters all instances by partial name match. |
|
public static |
Finds a single instance by partial name match. |
|
public static |
Gets an instance by its full name. |
|
public static |
Returns an object containing all instances as values. |
|
public static |
getSize(): * Retrieves the size of the occupied space for all instances. |
Constructor Summary
Public Constructor | ||
public |
constructor(name: String, options: Object) Creates a new Persistence object. |
Member Summary
Public Members | ||
public |
Whether to log details to the console when certain instance methods are called. |
Method Summary
Public Methods | ||
public |
clear() Empties the data object and the persisted backend values. |
|
public |
Persistently disables this instance. |
|
public |
enable() Persistently enables this instance. |
|
public |
Alias for |
|
public |
Retrieves a value from the backend data. |
|
public |
Gets the size of this storage. |
|
public |
Checks if a property exists. |
|
public |
Alias for |
|
public |
removeItem(key: String, autoSave: Boolean) Deletes a key and its value from the data object. |
|
public |
save() Writes the data object to backend |
|
public |
Alias for |
|
public |
Sets a key/value to the data object. |
|
public |
setItemValues(values: Object, autoSave: Boolean) Sets all values of a given object at once. |
Static Public Members
Static Public Methods
public static clearAll(options: Object) source
Clears the data of all instances.
Params:
Name | Type | Attribute | Description |
options | Object |
|
Options object |
options.only | Array |
|
An array of names. If provided, only instances whose names match partially will be cleared. |
options.not | Array |
|
An array of names. If provided, instances whose names match partially will NOT be cleared. |
public static connect(options: Object): Object source
Returns an already existing instance for a given name or creates a new instance and returns it. Note that all constructor options are supported here as well.
public static filter(name: string | RegExp): Array source
Filters all instances by partial name match.
public static find(name: string | RegExp): Object source
Finds a single instance by partial name match.
Example:
const instance = new Persistence('config', {publicPath: '/app-one/dev'});
console.log(Persistence.find('conf')) // {logging: false, save: ƒ, name: "[/app-one/dev]config", backend: Storage, defaultData: {…}, …}
public static get(name: String): Object source
Gets an instance by its full name.
The full name includes the publicPath
in order to avoid collisions in cases where multiple apps operate within the same origin.
For example, if you created an instance via new Persistence('foo')
, you could access it via Persistence.get('[/]foo')
.
On the other hand, you might also have a debuggable version deployed on the same origin at /dev
. (You'd probably use some kind of config value for publicPath
in such cases).
So, if you had created the instance via new Persistence('foo', {publicPath: '/dev'})
, you would access it via Persistence.get('[/dev]foo')
.
NOTE: If you do not want to deal with full names and publicPath
values, use Persistence.find(name)
instead.
NOTE: If you need to get all instances of the origin, use Persistence.filter(name)
instead.
Params:
Name | Type | Attribute | Description |
name | String | the full instance name |
public static getAll(): Object source
Returns an object containing all instances as values.
The instance names are used as keys. If you need an array of instances and don't care about their names, use Object.values(Persistence.getAll())
.
public static getSize(): * source
Retrieves the size of the occupied space for all instances. The value is a number of characters and roughly approximates bytes. TODO: proper byte-size conversion
Return:
* |
Public Constructors
public constructor(name: String, options: Object) source
Creates a new Persistence object.
A Persistence stores its data in a simple object (in memory) and persists the data as a JSON string to web storage backend (e.g. window.localStorage
) before the window unloads, using the instance name
as the actual key in the web storage backend.
When a new instance is created, it looks for previously stored data in the web storage backend, and parses it back to a data object for runtime usage.
This means that you can set and get values without an performance penalty, JSON conversion only happens at startup and before unload.
You can specify a name to enable multiple apps on the same origin without collisions in data using the publicPath
option.
(Consider that localStorage is shared per origin (protocol, host, port), so if you want to have two _instances in /a and /b, you can use those paths as names for the Persistence)
Params:
Name | Type | Attribute | Description |
name | String | A unique name for this backend object. |
|
options | Object | ||
options.data | Object | An initial data object for this instance |
|
options.backend | Object | The backend object to use as backend. Should expose |
|
options.logging | Boolean | Whether to enable to logging for this instance |
|
options.autoEnable | Boolean | Whether this instance should be enabled. Defaults to true. |
|
options.publicPath | String |
|
The path where this app is deployed within the current origin |
Public Members
Public Methods
public disable(autoClear: Boolean) source
Persistently disables this instance.
The data object will be cleared, setters will not change values anymore, save() will not write to the backend, and it will not be called before unload.
To only disable the functionality without flushing the data, pass false
as argument.
The disabled state will be persisted to backend: The instance remains inactive until enable()
is called, even across browser reload.
Params:
Name | Type | Attribute | Description |
autoClear | Boolean | Whether to remove the data as well. Defaults to true. |
public enable() source
Persistently enables this instance. Setters will change values, save will write to the backend, save() will be called before unload.
public get(key: String): any source
Alias for getItem(key)
Params:
Name | Type | Attribute | Description |
key | String | The key to retrieve a value for |
Return:
any | The value for |
public getItem(key: String): any source
Retrieves a value from the backend data.
- Booleans, numbers, undefined and null will be parsed/casted to proper JS objects/values
- All other values will be returned as strings
Note: This does not read from the backend directly, but from the data object instead (which was initially parsed from the backend values)
Params:
Name | Type | Attribute | Description |
key | String | The key to retrieve a value for |
Return:
any | The value for |
public has(key: String): Boolean source
Checks if a property exists.
Note: true
will be returned as long as the key is found on the data object, even if the value itself is empty.
Params:
Name | Type | Attribute | Description |
key | String | The property name to check for existence. |
public removeItem(key: String, autoSave: Boolean) source
Deletes a key and its value from the data object. Does not write to this.backend automatically!
public set(key: String | Object, value: any, autoSave: Boolean): * source
Alias for setItem(key, value)
Return:
* |
public setItem(key: String | Object, value: any, autoSave: Boolean): * source
Sets a key/value to the data object.
If the first argument is not a string but an object, the signature changes to (values, autoSave)
and setItemValues
will be used internally.
Return:
* |