Skip to content

Instantly share code, notes, and snippets.

@mrinterweb
Created September 16, 2014 23:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrinterweb/7e23a153a47c25adba1d to your computer and use it in GitHub Desktop.
Save mrinterweb/7e23a153a47c25adba1d to your computer and use it in GitHub Desktop.
Ember-data localforage record cache
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