Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

webStorage

georapbox111MITdeprecated2.1.1

This is no longer supported, please consider using https://github.com/georapbox/web-storage instead.

A minimal Javascript library that improves the way you work with localStorage or sessionStorage.

localStorage, sessionStorage, Storage, Offline Storage, Web Storage, DOM Storage

readme

webStorage

A minimal Javascript library that improves the way you work with localStorage or sessionStorage.

Build Status npm version npm downloads npm license Code Climate PRs Welcome Dependencies devDependency Status

Install

npm

$ npm install webStorage

Git

$ git clone https://github.com/georapbox/webStorage.git

A few words...

The purpose of this library is to allow the user to manipulate data to localStorage or sessionStorage accordingly using a namespace (default is "webStorage") as a prefix for each item's key. This is by design in order to avoid potential conflicts with other key/value pairs that are probably already saved to storage. So, for example, if the database name we provided is myApp, calling clear() will remove only the items with key prefix myApp. The same principle applies to all available API methods of the library.

API methods

config([options]) => WebStorage

Set and persist webStorage options. This must be called before any other calls to webStorage are made.

Kind: instance method of WebStorage
Throws: TypeError if options.name is not a string or empty string.
Throws: TypeError if options.keySeparator is not a string or empty string.
Returns: WebStorage - The WebStorage instance for chaining.

The following options can be set:

Option Type Description Default value
driver Object The preferred driver to use. Use one between localStorage and sessionStorage. localStorage
name String The name of the database. This is used as prefix for all keys stored in the offline storage. webStorage
keySeparator String String that separates database name and key. /

createInstance([options]) => WebStorage

Creates a new instance of the webStorage. The options can be the same as config(options).

Kind: instance method of WebStorage
Throws: TypeError if options.name is not a string or empty string.
Throws: TypeError if options.keySeparator is not a string or empty string.
Returns: WebStorage - The WebStorage instance for chaining.

getItem(key) => *

Gets a saved item from storage by its key.

Kind: instance method of WebStorage
Returns: * - The value of the saved item. If the key does not exist, will return null.

Param Type Default Description
key String |The property name of the saved item

setItem(key, [value]) => WebStorage

Saves an item to storage. You can store the following types of JavaScript objects:

  • String
  • Number
  • Array
  • Object

Kind: instance method of WebStorage
Returns: WebStorage - The WebStorage instance for chaining.

Param Type Default Description
key String |The property name of the item to save
[value] * null The item to save to the selected storage.

removeItem(key) => WebStorage

Removes the item for the specific key from the storage.

Kind: instance method of WebStorage
Returns: WebStorage - The WebStorage instance for chaining.

Param Type Default Description
key String |The property name of the item to remove

clear() => WebStorage

Removes all saved items from storage.

Kind: instance method of WebStorage
Returns: WebStorage - The WebStorage instance for chaining.

keys() => Array

Gets the list of all keys in the storage for a specific database.

Kind: instance method of WebStorage
Returns: Array - An array of all the keys that belong to a specific database.

length() => Number

Gets the number of items saved in a specific database.

Kind: instance method of WebStorage
Returns: Number - The number of items for a specific database.

iterate(iteratorCallback) => WebStorage

Iterate over all value/key pairs in datastore.

Kind: instance method of WebStorage
Returns: WebStorage - The WebStorage instance for chaining.

Param Type Default Description
iteratorCallback Function |A callabck function to be executed for each iteration

iteratorCallback is called once for each pair, with the following arguments:

Param Type Description
key String The key of the saved item.
value * The value of the saved item.

quota() => Object

Display (approximately) the size for each saved item in datastore and the total size of all items in MB.

Kind: instance method of WebStorage
Returns: Object<string,number> - An object with two properties that display the size for each saved item and the total size in MB.

supported() => Boolean

Checks if the driver of choice (localStorage or sessionStorage) is supported by the browser. It may return false if storage is full.

Kind: instance method of WebStorage
Returns: Boolean - True if driver is supported; otherwise false.

Usage Example

const users = [
  {id: 1, name: 'John Doe', email: 'johndoe@gmail.com'},
  {id: 2, name: 'George Cooper', email: 'gcooper@outlook.com'},
  {id: 2, name: 'Tim Smith', email: 'smith_t@yahoo.com'}
];

const companies = ['Google', 'Yahoo', 'Microsoft', 'Mozilla'];

/* Saving some items with the default configuration */
webStorage
  .setItem('user', users[0]);
  .setItem('company', companies[0]);

/* Create a new instance and save some items */
const ls = webStorage.createInstance({
  name: 'MyApp'
});

ls
  .setItem('user', users[1]);
  .setItem('company', companies[2]);
  .setItem('dummyKey', 100);

/* Retrieving saved items */
webStorage.getItem('user'); // -> Object { id: 1, name: "John Doe", email: "johndoe@gmail.com" }
webStorage.getItem('company'); // -> "Google"

ls.getItem('user'); // -> Object { id: 2, name: "George Cooper", email: "gcooper@outlook.com" }
ls.getItem('company'); // -> "Microsoft"

/* Get length of datastores */
webStorage.length(); // -> 2
ls.length(); // -> 3

/* Get datastores' keys */
webStorage.keys(); // -> Array [ "company", "user" ]
ls.keys(); // -> Array [ "dummyKey", "company", "user" ]

/* Itereate over datastores */
ls.iterate(function (key, value) {
  console.log(key, ':', value);
});
// -> dummyKey : 100
// -> company : Microsoft
// -> user : Object { id: 2, name: "George Cooper", email: "gcooper@outlook.com" }

/* Quota */
ls.quota();
// -> Object { "total": 0.0001430511474609375, "items": { "MyApp/dummyKey": 0.0000057220458984375, "MyApp/company": 0.0000209808349609375, "MyApp/user": 0.0001163482666015625 } }"

/* Removing items */
webStorage.removeItem('user');
webStorage.length(); // -> 1
webStorage.keys(); // -> Array [ "company" ]
ls.length(); // -> 3 (still same as before)
ls.clear(); /* Clear only the "MyApp" datastore */
ls.length(); // -> 0
ls.keys(); // -> Array []

Events

webStorage instances emit custom events the user can subscribe on:

  • setItem: When an item is saved in storage.
  • setItemError: When there is an error saving item to storage.
  • getItem: When an item is retrieved from storage.
  • getItemError: When there is an error retrieving an item from storage.
  • removeItem: When an item is removed from storage.
  • removeItemError: When there is an error removing an item from storage.
  • clear: When all items from a database are removed.

Example

const ls = webStorage.createInstance({
  name: 'MyApp'
});

function onItemSave(event) {
  // ...do something with event
}

// Subscribe to setItem event
ls.addEventListener('setItem', onItemSave);

// Unsubscribe to setItem event
ls.removeEventListener('setItem', onItemSave);

// Check if the target object has a listener registered on for specific event type
ls.hasEventListener('setItem', onItemSave);

Build for development

$ npm run dev

Build for production

$ npm run build

Test

$ npm test

Changelog

For API updates and breaking changes, check the CHANGELOG.

License

The MIT License (MIT)

changelog

2.1.1

  • [#3] Fix issue with config method that would not merge properly new options with the instance's options.

2.1.0

  • [#2] Ability to configure the separator between database name and key via keySeparator option.

2.0.0

Breaking changes

  • clear method no longer supports clearAll argument that used to flush everything in storage no matter the database name. If you need to do that use the native API of Storage, eg. localStorage.clear()
  • setItem, getItem and removeItem methods no longer throw errors explicitly. You can still catch any errors registering on the following events: setItemError, getItemError and removeItemError respectively.
  • iteratorCallback function no longer accepts iterationNumber as a third argument.

Other updates

  • removeItemError event is now emitted if there is an error while removing an item from storage.
  • config, setItem, removeItem, clear and iterate methods now return an instance reference for chaining purposes.
  • Keep devDependencies up to date.

1.2.4

  • Keep dependencies up to date
  • eslint loader for webpack

1.2.3

  • Change the way to update dependancies using the caret ^ strategy

1.2.2

  • Update ESLint rules
  • Add codeclimate configuration

1.2.1

  • Fix bug that caused custom events not to emit when using the default instance of webStorage
  • Keep devDependancies up to date

1.2.0

  • Emit custom events on specific operations

1.1.0

  • Rewrite using ES2015 syntax
  • Do not throw error on initialization if localStorage or sessionStorage is not supported or unavailable. User can still use the supported method to test for

1.0.0

Features

  • Add quota() public API method
  • Automate building distributable files in releases

0.5.3

Features

  • Add a "Usage Example" in documentation

Bug Fixes

  • Use JSON.parse to values on each iteration

0.5.2

Bug Fixes

  • Fix issue when trying to save item with undefined as value

0.5.1

Features

  • Add supported() method to public API, to check if the driver of choice is supported by the browser

0.5.0

Features

  • Add length() and iterate() public API methods
  • Make database name a required option to easily distinguish between different data stores
  • Remove comments (inline and block) and empty lines from production files

Bug Fixes

  • Fix issues with creating the keys prefixes from the database name