-
-
Save arenoir/528c4d77c9398e519984 to your computer and use it in GitHub Desktop.
localstorage cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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