js-data-localstorage

Localstorage adapter for JSData in the Browser

js-data-localstorage Slack Status npm version Circle CI npm downloads Coverage Status

See the DEMO.

Quick Start

npm install --save js-data js-data-localstorage or bower install --save js-data js-data-localstorage.

Load js-data-localstorage.js after js-data.js.

var adapter = new DSLocalStorageAdapter();

var store = new JSData.DS();
store.registerAdapter('localstorage', adapter, { default: true });

// "store" will now use the localstorage adapter for all async operations

Community & Links

API

new DSLocalStorageAdapter([options])

📘

Need help?

Want more examples or have a question? Ask on the Slack channel or post on the mailing list then we'll get your question answered and probably update this wiki.

Default Settings

When you create a new instance of DSLocalStorageAdapter it will come with some defaults. Here they are:

basePath

Type: string

Base path to use for item keys.

Default: ""

create(resourceConfig, attrs[, options])

Creates a new item in localstorage.

Returns a promise.

ArgumentTypeDescription
resourceConfigobjectThe Resource definition created by DS#defineResource.
attrsobjectThe attributes from which to create the item.
optionsobjectOptional configuration.
options.basePathstringOverride the basePath. Default: resourceConfig.basePath.
options.endpointstringOverride the endpoint. Default: resourceConfig.endpoint.
Examples
var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('ls', adapter, { default: true });

var Document = store.defineResource('document');

// bypass the data store
adapter.create(Document, { author: 'John' }).then(function (document) {
  document; // { id: 5, author: 'John' }
  
  // The new document has NOT been injected into the data store because we bypassed the data store
  Document.get(document.id); // undefined
});

// Normally you would just go through the data store
Document.create({ author: 'John' }).then(function (document) {
  document; // { id: 5, author: 'John' }
  
  // the new document has been injected into the data store
  Document.get(document.id); // { id: 5, author: 'John' }
});

DEL(path[, options])

Asynchronous wrapper for localStorage.removeItem(key).

Returns a promise.

Arguments
nametypedescription
keystringKey of item to remove.
Examples
var adapter = new DSLocalStorageAdapter();

adapter.DEL('/user/1').then(...);

destroy(resourceConfig, id[, options])

Delete an item from localstorage.

Returns a promise.

Arguments
nametypedescription
resourceConfigobjectThe resource definition created by DS#defineResource.
idstring or numberThe primary key of the item to destroy.
optionsobjectConfiguration options. Also passed through to DSLocalStorageAdapter#DEL.
options.basePathstringOverride the basePath. Default: resourceConfig.basePath.
options.endpointstringOverride the endpoint. Default: resourceConfig.endpoint.
Examples
var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('ls', adapter, { default: true });

var Document = store.defineResource('document');

Document.inject({ id: 5, author: 'John' });

// bypass the data store
adapter.destroy(Document, 5).then(function () {
  // the document is still in the data store because we bypassed the data store
  Document.get(document.id); // { id: 5, author: 'John' }
});

// Normally you would just go through the data store
Document.destroy(5).then(function () {
  // the document has been ejected from the data store
  Document.get(document.id); // undefined
});

destroyAll(resourceConfig, params[, options])

Delete a collection of items from localstorage.

Returns a promise.

Arguments
nametypedescription
resourceConfigobjectThe resource definition created by DS#defineResource.
paramsobjectQuery parameters for selecting the items to destroy. Default: {}.
optionsobjectConfiguration options. Also passed through to DSLocalStorageAdapter#GET.
options.basePathstringOverride the basePath. Default: resourceConfig.basePath.
options.endpointstringOverride the endpoint. Default: resourceConfig.endpoint.
Examples
var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('ls', adapter, { default: true });

var Document = store.defineResource('document');

var params = {
  author: 'John'
};

// bypass the data store
adapter.destroyAll(Document, params).then(function () {
  // the documents have NOT been ejected from the data store because we bypassed the data store
  Document.filter(params); // [{...}, {...}, ...]
});

// normally you would go through the data store
Document.findAll(params).then(function () {
  // the documents have been ejected from the data store
  Document.filter(params); // []
});

find(resourceConfig, id[, options])

Get an item from localstorage.

Returns a promise.

ArgumentTypeDescription
resourceConfigobjectThe Resource definition created by DS#defineResource.
idstring or numberThe primary key of the item to retrieve.
optionsobjectConfiguration options.
options.basePathstringOverride the basePath. Default: resourceConfig.basePath.
options.endpointstringOverride the endpoint. Default: resourceConfig.endpoint.
options.witharray of stringsArray of relation names or relation field names to eager load with the retrieved item. Supports nested relations, e.g. adapter.find(Post, 1, { with: ['user.organization'] })
Examples
var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('ls', adapter, { default: true });

var Document = store.defineResource({
  name: 'document',
  relations: {
    belongsTo: {
      user: {
        localKey: 'userId',
        localField: 'user'
      }
    }
  }
});
var User = store.defineResource({
  name: 'user',
  relations: {
    hasMany: {
      document: {
        foreignKey: 'userId',
        localField: 'documents'
      }
    },
    belongsTo: {
      organization: {
        localKey: 'organizationId',
        localField: 'organization'
      }
    }
  }
});
var Organization = store.defineResource({
  name: 'organization',
  relations: {
    hasMany: {
      user: {
        foreignKey: 'organizationId',
        localField: 'users'
      }
    }
  }
});

// bypass the data store
adapter.find(Document, 5, { with: ['user'] }).then(function (document) {
  document; // { id: 5, content: 'foo', userId: 1, user: {...} }
  document.user; // { id: 1, name: 'John Anderson' }
});

// Normally you would just go through the data store
Document.find(5, { with: ['user', 'user.organization'] }).then(function (document) {
  document; // { id: 5, content: 'foo', userId: 1, user: {...} }
  document.user; // { id: 1, name: 'John Anderson', organizationId: 10 }
  document.user.organization; // { id: 10, name: 'Company' }
});

findAll(resourceConfig, params[, options])

Get a collection of items from localstorage.

Returns a promise.

ArgumentTypeDescription
resourceConfigobjectThe Resource definition created by DS#defineResource.
paramsobjectQuery parameters for selecting the items to retrieve, limit, sort, etc. See Query Syntax. Default: { }
optionsobjectOptional configuration.
options.basePathstringOverride the basePath. Default: resourceConfig.basePath.
options.endpointstringOverride the endpoint. Default: resourceConfig.endpoint.
options.witharray of stringsArray of relation names or relation field names to eager load with the retrieved items. Supports nested relations, e.g. adapter.findAll(Post, 1, { with: ['user.organization'] })
Examples
var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('ls', adapter, { default: true });

var Document = store.defineResource({
  name: 'document',
  relations: {
    belongsTo: {
      user: {
        localKey: 'userId',
        localField: 'user'
      }
    }
  }
});
var User = store.defineResource({
  name: 'user',
  relations: {
    hasMany: {
      document: {
        foreignKey: 'userId',
        localField: 'documents'
      }
    },
    belongsTo: {
      organization: {
        localKey: 'organizationId',
        localField: 'organization'
      }
    }
  }
});
var Organization = store.defineResource({
  name: 'organization',
  relations: {
    hasMany: {
      user: {
        foreignKey: 'organizationId',
        localField: 'users'
      }
    }
  }
});

var params = {
  size: {
    '>': 15000000
  }
};

// bypass the data store
adapter.findAll(Document, params).then(function (documents) {
  documents[0].size; 15063940
});

// normally you would go through the data store
Document.findAll(params).then(function (documents) {
  documents[0].size; 94839687
});

adapter.findAll(Document, params, { with: ['user', 'user.organization'] }).then(function (documents) {
  documents[0].size;
  documents[0].user; // {...}
  documents[0].user.organization; // {...}
});

GET(key)

Asynchronous wrapper for localStorage.getItem.

Returns a promise.

ArgumentTypeDescription
keystringThe key of the item to retrieve from localStorage.
Examples
var adapter = new DSLocalStorageAdapter();

adapter.GET('/user/1').then(function (data) {
  // ...
});

PUT(key, value)

Asynchronous wrapper for localStorage.setItem(key, value)

Returns a promise.

ArgumentTypeDescription
keystringKey of item to put into localStorage.
valuestringThe value to put into localStorage.
Examples
var adapter = new DSLocalStorageAdapter();

adapter.PUT('/user/1', { name: 'Johnny' }).then(...);

update(resourceConfig, id, attrs[, options])

Update an item in localstorage.

Returns a promise.

Arguments
nametypedescription
resourceConfigobjectThe resource definition created by DS#defineResource.
idstring or numberThe primary key of the item to retrieve.
attrsobjectThe attributes with which to update the item.
optionsobjectConfiguration options. Also passed through to DSLocalStorageAdapter#PUT.
options.basePathstringOverride the basePath. Default: resourceConfig.basePath.
options.endpointstringOverride the endpoint. Default: resourceConfig.endpoint.
Examples
var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('ls', adapter, { default: true });

var Document = store.defineResource('document');

Document.inject({ id: 5, author: 'John' });

// bypass the data store
adapter.update(Document, 5, { author: 'Johnny' }).then(function (document) {
  document; // { id: 5, author: 'Johnny' }
  
  // The updated document has NOT been injected into the data store because we bypassed the data store
  Document.get(document.id); // { id: 5, author: 'John' }
});

// Normally you would just go through the data store
Document.update(5, { author: 'Johnny' }).then(function (document) {
  document; // { id: 5, author: 'Johnny' }
  
  // the updated document has been injected into the data store
  Document.get(document.id); // { id: 5, author: 'Johnny' }
});

updateAll(resourceConfig, attrs, params[, options])

Update a collection of items in localstorage.

Returns a promise.

Arguments
nametypedescription
resourceConfigobjectThe resource definition created by DS#defineResource.
attrsobjectThe attributes with which to update the items.
paramsobjectQuery parameters for selecting the items to update. Default: {}.
optionsobjectConfiguration options. Also passed through to DSLocalStorageAdapter#PUT.
options.basePathstringOverride the basePath. Default: resourceConfig.basePath.
options.endpointstringOverride the endpoint. Default: resourceConfig.endpoint.
Examples
var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('ls', adapter, { default: true });

var Document = store.defineResource('document');

Document.inject({ id: 5, author: 'John' });
Document.inject({ id: 6, author: 'John' });

// bypass the data store
adapter.updateAll(Document, { author: 'Johnny' }, { author: 'John' }).then(function (documents) {
  documents[0]; // { id: 5, author: 'Johnny' }
  
  // The updated documents have NOT been injected into the data store because we bypassed the data store
  Document.filter({ author: 'John' }); // [{...}, {...}]
  Document.filter({ author: 'Johnny' }); // []
});

// Normally you would just go through the data store
Document.updateAll({ author: 'Johnny' }, { author: 'John' }).then(function (documents) {
  documents[0]; // { id: 5, author: 'Johnny' }
  
  // the updated documents have been injected into the data store
  Document.filter({ author: 'John' }); // []
  Document.filter({ author: 'Johnny' }); // [{...}, {...}]
});

📘

License

The MIT License (MIT)

Copyright (c) 2014-2015 Jason Dobry

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.