angular-cached-resource
Version:
An AngularJS module to interact with RESTful resources, even when browser is offline
70 lines (49 loc) • 1.82 kB
text/coffeescript
{localStorage} = window
class Cache
memoryCache: {}
constructor: ({@$log, }) ->
getItem: (key, fallbackValue) ->
key = key
item = [key]
item ?= localStorage.getItem key
out = if item? then angular.fromJson(item) else fallbackValue
@$log.debug "CACHE GET: #{key}", out
out
setItem: (key, value) ->
key = key
stringValue = angular.toJson value
try
localStorage.setItem(key, stringValue)
delete [key] if [key]?
catch
[key] = stringValue
@$log.debug "CACHE PUT: #{key}", angular.fromJson angular.toJson value
value
clear: ({key, exceptFor, where} = {}) ->
return @$log.error "Using where and exceptFor arguments at once in clear() method is forbidden!" if where && exceptFor
if exceptFor
exceptFor ?= []
cacheKeys = []
for i in [0...localStorage.length]
cacheKey = localStorage.key i
continue unless
skipKey = no
for exception in exceptFor when
skipKey = yes
break
continue if skipKey
cacheKeys.push cacheKey
localStorage.removeItem(cacheKey) for cacheKey in cacheKeys
else
for cacheKey in where
localStorage.removeItem cacheKey
_buildKey: (key) ->
"#{@localStoragePrefix}#{key}"
_cacheKeyHasPrefix: (cacheKey, prefix) ->
return cacheKey.indexOf() is 0 unless prefix?
prefix = prefix
index = cacheKey.indexOf prefix
nextChar = cacheKey[prefix.length]
index is 0 and (not nextChar? or nextChar in ['?', '/'])
module.exports = (providerParams) ->
new Cache(providerParams)