bonestore
v1.0.0
Published
Simple app data management
Downloads
3
Readme
Bonestore
Simple app data management.
Installing
Using npm:
$ npm install bonestore
Example
First create Bonestore
instance.
It will be used to hold stores and provide default adapter.
import Bonestore, { Store, CollectionStore, HttpRestAdapter } from 'bonestore';
const data = new Bonestore({
defaultAdapter: new HttpRestAdapter({
baseURL: 'https://api.example.com/v1/',
}),
});
Next define stores
// Simple data object { key: value }
data.defineStore('permissions', new Store());
// Collection of objects [{key: value}, …]
data.defineStore('posts', new CollectionStore());
Finally you can read/create/update/delete
data.getStore('permissions')
.find() // GET https://api.example.com/v1/permissions
.then((permissions) => {
permissions.roles;
});
data.getStore('posts')
.findAll() // GET https://api.example.com/v1/posts
.then((postsArray) => {
postsArray;
});
data.getStore('posts')
.find(321) // GET https://api.example.com/v1/posts/321
.then((post) => {
post;
});
data.getStore('posts')
.create({ title: 'Lorem' }) // POST https://api.example.com/v1/posts
.then((post) => {
post.id; // new id from backend
post.title; // 'Lorem'
});
Watch store changes
data.onStoreChange('posts', (storeName, changeType, payload) => {
console.log('Posts changed', changeType, payload);
})
API
Bonestore(config)
Configuration
defaultAdapter: adapterInstance
- default adapter for defined stores
Methods
defineStore(storeName, storeInstance)
- define storegetStore(storeName)
- return defined storeonStoreChange(storeName, callback)
- listen for changes in specific storeoffStoreChange(storeName, callback)
- stop listenemitChange(storeName, changeType, payload)
- emmit store change (for internal use in stores)
Stores
new Store(config)
find(params)
- find objectcreate(obj, params)
- overwriteupdate(obj, params)
- updatedelete(params)
- remove (empty object)
new CollectionStore(config)
find(id, params)
- find one itemfindAll(params)
- find list of itemscreate(obj, params)
- create new objectupdate(obj, params)
- update existing item (id must be provided)save(obj, params)
- update or create item when id does not existsdelete(id, params)
- delete one item
Store configuration
adapter: adapterInstance
- (optional) adapter instance
Warning: params
currently only work with HTTP adapter and are sent as query string.
Adapters
new MemoryAdapter()
new LocalStorageAdapter({
prefix: 'my_app_', // default ''
})
new HttpRestAdapter({
baseURL: '',
timeout: 2000, // default 10s
headers: {},
})
Extending stores
If you need more complex functionality, you can extend the Store class.
// PostsStore.js
class PostsStore extends CollectionStore {
findUserPosts(userId) {
return this.findAll({ user: userId });
}
}
// data.js
data.defineStore('posts', new PostsStore());