UNPKG

1.91 kBtext/coffeescriptView Raw
1{localStorage} = window
2
3class Cache
4 memoryCache: {}
5
6 constructor: ({@$log, @localStoragePrefix}) ->
7
8 getItem: (key, fallbackValue) ->
9 key = @_buildKey key
10
11 item = @memoryCache[key]
12 item ?= localStorage.getItem key
13
14 out = if item? then angular.fromJson(item) else fallbackValue
15 @$log.debug "CACHE GET: #{key}", out
16
17 out
18
19 setItem: (key, value) ->
20 key = @_buildKey key
21 stringValue = angular.toJson value
22
23 try
24 localStorage.setItem(key, stringValue)
25 delete @memoryCache[key] if @memoryCache[key]?
26 catch e
27 @$log.error "Failed to write to localStorage.", {error: e, key, value: stringValue}
28 @memoryCache[key] = stringValue
29
30 @$log.debug "CACHE PUT: #{key}", angular.fromJson angular.toJson value
31
32 value
33
34 clear: ({key, exceptFor, where} = {}) ->
35 return @$log.error "Using where and exceptFor arguments at once in clear() method is forbidden!" if where && exceptFor
36
37 if exceptFor
38 exceptFor ?= []
39
40 cacheKeys = []
41 for i in [0...localStorage.length]
42 cacheKey = localStorage.key i
43 continue unless @_cacheKeyHasPrefix(cacheKey, key)
44
45 skipKey = no
46 for exception in exceptFor when @_cacheKeyHasPrefix(cacheKey, exception)
47 skipKey = yes
48 break
49
50 continue if skipKey
51 cacheKeys.push cacheKey
52
53 localStorage.removeItem(cacheKey) for cacheKey in cacheKeys
54 else
55 for cacheKey in where
56 localStorage.removeItem @_buildKey cacheKey
57
58 _buildKey: (key) ->
59 "#{@localStoragePrefix}#{key}"
60
61 _cacheKeyHasPrefix: (cacheKey, prefix) ->
62 return cacheKey.indexOf(@localStoragePrefix) is 0 unless prefix?
63 prefix = @_buildKey prefix
64 index = cacheKey.indexOf prefix
65 nextChar = cacheKey[prefix.length]
66 index is 0 and (not nextChar? or nextChar in ['?', '/'])
67
68
69module.exports = (providerParams) ->
70 new Cache(providerParams)