-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcache.coffee
More file actions
70 lines (50 loc) · 1.88 KB
/
cache.coffee
File metadata and controls
70 lines (50 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{localStorage} = window
class Cache
memoryCache: {}
constructor: ({@$log, @localStoragePrefix}) ->
getItem: (key, fallbackValue) ->
key = @_buildKey key
item = @memoryCache[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 = @_buildKey key
stringValue = angular.toJson value
try
localStorage.setItem(key, stringValue)
delete @memoryCache[key] if @memoryCache[key]?
catch e
@$log.error "Failed to write to localStorage.", {error: e, key, value: stringValue}
@memoryCache[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 cacheKey and @_cacheKeyHasPrefix(cacheKey, key)
skipKey = no
for exception in exceptFor when @_cacheKeyHasPrefix(cacheKey, exception)
skipKey = yes
break
continue if skipKey
cacheKeys.push cacheKey
localStorage.removeItem(cacheKey) for cacheKey in cacheKeys
else
for cacheKey in where
localStorage.removeItem @_buildKey cacheKey
_buildKey: (key) ->
"#{@localStoragePrefix}#{key}"
_cacheKeyHasPrefix: (cacheKey, prefix) ->
return cacheKey.indexOf(@localStoragePrefix) is 0 unless prefix?
prefix = @_buildKey prefix
index = cacheKey.indexOf prefix
nextChar = cacheKey[prefix.length]
index is 0 and (not nextChar? or nextChar in ['?', '/'])
module.exports = (providerParams) ->
new Cache(providerParams)