Skip to content

Instantly share code, notes, and snippets.

@jmdobry
Last active May 16, 2018 18:16
Show Gist options
  • Save jmdobry/cf489a3025b8087fe21a to your computer and use it in GitHub Desktop.
Save jmdobry/cf489a3025b8087fe21a to your computer and use it in GitHub Desktop.
js-data + js-data-firebase + js-data-localstorage
var fb = new DSFirebaseAdapter({
basePath: 'https://my-app.firebase.io'
});
var ls = new DSLocalStorageAdapter();
var store = new JSData.DS({
// try firebase first, otherwise try offline data
fallbackAdapters: ['fb', 'ls'],
// After creating an item, sync it to localStorage
afterCreate: function (resource, data) {
return ls.create(resource, data);
},
// After updating an item, sync it to localStorage
afterUpdate: function (resource, data) {
if (typeof data === 'array') {
return Promise.all(data.map(function (item) {
return ls.update(resource, item[resource.idAttribute], item);
}));
} else {
return ls.update(resource, data[resource.idAttribute], data);
}
},
// After destroying an item, sync it to localStorage
afterDestroy: function (resource, data) {
if (typeof data === 'array') {
return Promise.all(data.map(function (item) {
return ls.destroy(resource, item[resource.idAttribute], item);
}));
} else {
return ls.destroy(resource, data[resource.idAttribute], data);
}
}
});
store.registerAdapter('ls', ls);
store.registerAdapter('fb', fb, { default: true });
// define resources
var User = store.defineResource('user');
var Post = store.defineResource('post');
var Comment = store.defineResource('comment');
// load all data from localStorage into the data store
Promise.all([
User.findAll({}, { adapter: 'ls' }),
Post.findAll({}, { adapter: 'ls' }),
Comment.findAll({}, { adapter: 'ls' })
]).then(function (data) {
data[0]; // all users already in localStorage
data[1]; // all posts already in localStorage
data[2]; // all comments already in localStorage
})
function isOffline() {
// return whether the app is "offline"
}
// From here on the firebase adapter will be used by default.
// Unless you specify a different adapter during a method call...
function chooseAdapter() {
return isOffline() ? 'ls' : 'fb';
}
// so you can do this:
User.find(1, { adapter: chooseAdapter() }).then(function (user) {
if (isOffline()) {
// then "user" was loaded from localStorage
} else {
// then "user" was loaded from Firebase
}
});
// or this:
// try firebase, if fails, try localstorage
User.find(1, { strategy: 'fallback' }).then(function (user) {
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment