Created
September 16, 2014 23:44
-
-
Save mrinterweb/7e23a153a47c25adba1d to your computer and use it in GitHub Desktop.
Ember-data localforage record 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
App.Cache = Em.Object.extend | |
init: -> | |
@store = App.__container__.lookup('store:main') | |
# tries to load the results from localforage cache or from normal adapter | |
findAll: -> | |
localforage.getItem(@modelStr).then (cacheItems)=> | |
if Em.isEmpty(cacheItems) | |
@findAndCache() | |
else | |
allRecords = @store.all(@modelStr) | |
if Em.isEmpty allRecords | |
cacheItems.map (cacheItem)=> | |
@store.createRecord(@modelStr, cacheItem) | |
else | |
allRecords | |
# finds all records and caches with localforage | |
findAndCache: -> | |
@store.find(@modelStr).then (records)=> | |
cacheRecords = records.map (record)=> | |
@serializer(record) | |
localforage.setItem(@modelStr, cacheRecords.compact()) | |
records | |
# clears cache and reloads all records | |
reloadAll: -> | |
localforage.removeItem(@modelStr).then => | |
@findAndCache() | |
# example implemention | |
App.FriendCache = App.Cache.extend | |
init: -> | |
@_super() | |
@modelStr = 'friend' | |
@serializer = (friend)-> | |
if friend.id | |
s = friend.serialize() | |
s.id = friend.id | |
s.group_ids = friend._data.groups.mapBy('id') | |
s | |
# Example invocation | |
App.FriendCache.create().findAll() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment