Skip to content

Instantly share code, notes, and snippets.

@arenoir
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arenoir/528c4d77c9398e519984 to your computer and use it in GitHub Desktop.
Save arenoir/528c4d77c9398e519984 to your computer and use it in GitHub Desktop.
localstorage cache
import Ember from 'ember';
var computed = Ember.computed;
var get = Ember.get;
export default Ember.Mixin.create({
maxUpdatedAt: function() {
var max;
var key = 'updatedAt';
return this.reduce(function(value, item) {
max = get(item, key);
if (max && max > value) {
return max;
}
return value;
}, null);
}.property('[]'),
setup: function() {
var _this = this;
var store = this.store;
var type = this.get('recordType');
return new Ember.RSVP.Promise(function(resolve, reject) {
var loading = _this.loadFromCache();
loading.then( function() {
var max = _this.get('maxUpdatedAt');
store.find(type, {updated_after: max}).then(function(results) {
if (results.get('content.length') > 0) {
_this.saveToCache();
}
resolve(results);
});
});
});
},
saveToCache: function() {
var type = this.get('recordType');
var collection = this.store.all(type);
var records = collection.map(function(item) {
return item.toJSON({includeId: true});
});
return new Ember.RSVP.Promise(function(resolve, reject) {
localStorage.setItem(type, JSON.stringify(records));
resolve();
});
},
loadFromCache: function() {
var _this = this;
var type = this.get('recordType');
var t = moment().valueOf();
return new Ember.RSVP.Promise(function(resolve, reject) {
var value = localStorage.getItem(type);
var payload = {};
if (value) {
payload[type] = JSON.parse(value);
_this.store.pushPayload(type, payload);
}
resolve();
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment