Home Reference Source
public class | source

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

clearAll(options: Object)

Clears the data of all instances.

public static

connect(options: Object): Object

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

find(name: string | RegExp): Object

Finds a single instance by partial name match.

public static

get(name: String): Object

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

disable(autoClear: Boolean)

Persistently disables this instance.

public

enable()

Persistently enables this instance.

public

get(key: String): any

Alias for getItem(key)

public

getItem(key: String): any

Retrieves a value from the backend data.

public

Gets the size of this storage.

public

has(key: String): Boolean

Checks if a property exists.

public

remove(key: String, autoSave: Boolean): *

Alias for removeItem(key)

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

set(key: String | Object, value: any, autoSave: Boolean): *

Alias for setItem(key, value)

public

setItem(key: String | Object, value: any, autoSave: Boolean): *

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

public static get instances: Array source

An array containing all instances. NOTE: This is a read-only value. You can not mutate the actual instances array.

public static logging: Boolean source

Whether to log details to the console when certain static methods are called.

Static Public Methods

public static clearAll(options: Object) source

Clears the data of all instances.

Params:

NameTypeAttributeDescription
options Object
  • optional

Options object

options.only Array
  • optional

An array of names. If provided, only instances whose names match partially will be cleared.

options.not Array
  • optional

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.

Params:

NameTypeAttributeDescription
options Object
  • optional

Options object

options.publicPath String
  • optional
  • default: '/'

The path where this app is deployed within the current origin

Return:

Object

The found or created Persistence object

public static filter(name: string | RegExp): Array source

Filters all instances by partial name match.

Params:

NameTypeAttributeDescription
name string | RegExp

A string or regular expression that will be matched against instance names

Return:

Array

An array of matching Persistence objects. Might be empty.

public static find(name: string | RegExp): Object source

Finds a single instance by partial name match.

Params:

NameTypeAttributeDescription
name string | RegExp

A string or regular expression that will be matched against instance names

Return:

Object

The found Persistence object or undefined

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:

NameTypeAttributeDescription
name String

the full instance name

Return:

Object

The found Persistence object or undefined

See:

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()).

Return:

Object

A key/value object where each key is an instance name and each value is an instance.

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:

NameTypeAttributeDescription
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 getItem, getItem and removeItem function. Defaults to window.localStorage.

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
  • optional
  • default: '/'

The path where this app is deployed within the current origin

Public Members

public logging: Boolean source

Whether to log details to the console when certain instance methods are called.

Public Methods

public clear() source

Empties the data object and the persisted backend values.

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:

NameTypeAttributeDescription
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:

NameTypeAttributeDescription
key String

The key to retrieve a value for

Return:

any

The value for key

See:

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:

NameTypeAttributeDescription
key String

The key to retrieve a value for

Return:

any

The value for key

public getSize(): number source

Gets the size of this storage. Seems to approximate bytes.

Return:

number

The number of characters used to store the stringified data.

See:

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:

NameTypeAttributeDescription
key String

The property name to check for existence.

Return:

Boolean

true if key was found

public remove(key: String, autoSave: Boolean): * source

Alias for removeItem(key)

Params:

NameTypeAttributeDescription
key String

The key to delete

autoSave Boolean

Whether to write to backend. Defaults to false

Return:

*

See:

public removeItem(key: String, autoSave: Boolean) source

Deletes a key and its value from the data object. Does not write to this.backend automatically!

Params:

NameTypeAttributeDescription
key String

The key to delete

autoSave Boolean

Whether to write to backend. Defaults to false

public save() source

Writes the data object to backend

public set(key: String | Object, value: any, autoSave: Boolean): * source

Alias for setItem(key, value)

Params:

NameTypeAttributeDescription
key String | Object

The key for the value

value any
  • optional

When key is a string: the value, otherwise: the autoSave flag

autoSave Boolean
  • optional

When key is a string: Whether to immediatly write to the backend.

Return:

*

See:

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.

Params:

NameTypeAttributeDescription
key String | Object

The key for the value

value any
  • optional

When key is a string: the value, otherwise: the autoSave flag

autoSave Boolean
  • optional

When key is a string: Whether to immediatly write to the backend.

Return:

*

public setItemValues(values: Object, autoSave: Boolean) source

Sets all values of a given object at once. Calls set(key, value) for each key of the object.

Params:

NameTypeAttributeDescription
values Object

An object with keys and values

autoSave Boolean

Whether to write to the storage backend right away.