π¦ depot.js
Description
depot.js is a namespaced localStorage wrapper with a simple API. There are other tools out there but none of them had what I was looking for.
Setup
You can install depot.js via npm:
npm install depotjs --save
or load it directly via <script src="depot.browser.js"></script>
. The dist
folder contains the most recent minified browser version depot.browser.js
.
Dependencies
depot.js does not depend on any other libraries however if you plan to support older browsers you will need to include ES5-shim.
If you plan to run it on browsers that don't support localStorage you may try to include storage polyfill.
API
-
save(record)
-
saveAll(array)
-
updateAll(hash)
-
update(hash)
-
find(hash | function)
-
all()
-
destroy(id | record)
-
destroyAll(none | hash | function)
-
get(id)
-
size()
Usage
Import depot
import depot from 'depotjs';
Define new store
const todos = depot('todos');
Add new records
_id
property will be generated as GUID and attached to each new record:
todos.save({ title: "todo1" });
todos.save({ title: "todo2", completed: true });
todos.save({ title: "todo3", completed: true });
Add multiple records at once
todos.saveAll([ { title: "todo1" }, { title: "todo2" }, { title: "todo3" } ]);
Update all records
todos.updateAll({ completed: false });
Return all records
todos.all(); // [{ _id: 1, title "todo1" }, { _id: 2, title: todo2 }]
Find records
- find based on given criteria
todos.find({ completed: true }); // [{ _id: 2, title: "todo2" }, { _id: 3, title: "todo3" }]
- find based on given function
todos.find(record => record.completed && record.title == "todo3"); // [{ _id: 3, title: "todo3" }]
Return single record by id
todos.get(1); // { _id: 1, title: "todo1" }
Destroy single record
- by record id
todos.destroy(1);
- by record object
todos.destroy(todo);
Destroy all records
- destroy all
todos.destroyAll();
- destroy by given criteria
todos.destroyAll({ completed: true });
- destroy by given function
todos.destroyAll(record => record.completed && record.title === "todo3");
Options
You can pass a second parameter to depot
with additional options.
const todos = depot("todos", options);
Available options:
- idAttribute - used to override record id property (default:
_id
)
const todos = depot("todos", { idAttribute: 'id' });
- storageAdaptor - used to override storage type (default:
localStorage
)
const todos = depot('todos', { storageAdaptor: sessionStorage });
License:
The MIT License