This repository has been archived by the owner on Jun 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
locache.0.1.0.js
364 lines (279 loc) · 11.5 KB
/
locache.0.1.0.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*jshint asi:true */
// locache 0.1.0
//
// (c) 2012 Dougal Matthews
// locache may be freely distributed under the MIT licence.
//
// locache is a client side caching framework that stores data
// is localStorage and proves a memcache inspired API for
// setting and retrieving values.
//
(function(){
"use strict";
// Initial Setup
// --------------------
// Save a reference to the global window object.
var root = this
// The top-level namespace. All public locache objects will be
// attached to this object.
var locache = {}
// Attach the locache namespace to the global window object.
root.locache = locache
// Current version of locache. Keep this in sync with the version
// at the top of this file.
locache.VERSION = "0.1.0"
// Boolean value that determines if they browser supports localStorage or
// not. This is based on the Modernizr implementation that can be found
// in [the Modernizr GitHub repository.](https://github.com/Modernizr/Modernizr/blob/c56fb8b09515f629806ca44742932902ac145302/modernizr.js#L696-731)
locache.supportsLocalStorage = (function() {
try {
// Create a test value and attempt to set, get and remove the
// value. These are the core functionality required by locache.
var test_val = "___locache___"
localStorage.setItem(test_val, test_val)
localStorage.getItem(test_val)
localStorage.removeItem(test_val)
// If any of the checks fail, an exception will be raised. At
// that point we can flag the browser as not supporting
// localStorage.
return true
} catch(e) {
return false
}
})()
// Boolean flag to check if the browser supports native JSON.
locache.supportsNativeJSON = !!window.JSON
// Internal utility functions
// --------------------
// Two cache prefixes. When storing values, all keys are prefixed
// to avoid collisions with other usage of localStorage. If the
// stored value is given an expire time then a second key is set
// with a different prefix to store this time.
locache.cachePrefix = '___locache___'
locache.expirePrefix = '___locacheExpire___'
// A simple wrapper around localStorage for usage interlally within
// locache. This is added to offer a level of abstraction so the
// storage system can be changed to support any browser oddities.
locache.storage = {
set : function(key, value){
return localStorage.setItem(key, value)
},
get : function(key, value){
return localStorage.getItem(key)
},
remove : function(key){
return localStorage.removeItem(key)
},
length : function(key){
return localStorage.length
},
key : function(index){
if (index < 0 || index >= this.length()){
return
}
return localStorage.key(index)
}
}
// Utility method to get the number of milliseconds since the Epoch. This
// is used when comparing keys to see if they have expired.
var _currentTime = function(){
return new Date().getTime()
}
// Given a key, return the key used internally for storing values without
// the risk of collisions over usage of localStorage.
locache.key = function(key){
return this.cachePrefix + key
}
// Given a key, return the key to be used internally for expiry time.
locache.expirekey = function(key){
return this.expirePrefix + key
}
// Given a key, look up its expire time and determine if its in the past
// or not. Returns a Boolean.
locache.hasExpired = function(key){
var expireKey = this.expirekey(key)
var expireValue = parseInt(this.storage.get(expireKey), 10)
// If we have non-zero integer perform the comparison.
if (expireValue && expireValue < _currentTime()){
return true
}
return false
}
// Main public API functions.
// --------------------
// Given a key, a value and an optional number of seconds store the value
// in localStorage.
locache.set = function(key, value, seconds){
// If localStorage isn't supported or the key passed in is falsy,
// perform a no-op.
if (!this.supportsLocalStorage || !key) return
var expireKey = this.expirekey(key)
var valueKey = this.key(key)
if(seconds){
// The time stored is in milliseconds, but this function expects
// seconds, so multiply by 1000.
var ms = seconds * 1000
this.storage.set(expireKey, _currentTime() + ms)
}
// For the value, always convert it into a JSON object. THis means
// that we can safely store many types of objects. They still need to
// be serialisable so it still rules out some, such as functions.
value = JSON.stringify(value)
this.storage.set(valueKey, value)
}
// Fetch a value from the cache. Either returns the value, or if it
// doesn't exist (or has expired) return null.
locache.get = function(key){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return null
// If the value has expired, before returning null remove the key
// from localStorage to free up the space.
if (this.hasExpired(key)){
this.remove(this.key(key))
return null
}
var valueKey = this.key(key)
var value = this.storage.get(valueKey)
// After we have the value back, check its truthy and then attempt to
// parse the JSON. If the JSON parsing fails, return null. This could
// be handled better but its hard to know what to do here? We only
// set JSON and thus we expect JSON but we don't want to delete
// values that must have come from another source.
if (value){
try{
return JSON.parse(value)
} catch(err){
return null
}
}
// If value isn't truthy, it must be an empty string or similar, so
// just return that.
return value
}
// When removing a key - delete from the storage both the value key/value
// pair and the expiration time key/value pair.
locache.remove = function(key){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return
var expireKey = this.expirekey(key)
var valueKey = this.key(key)
this.storage.remove(expireKey)
this.storage.remove(valueKey)
}
// Given a key name, fetch it, increment the value and store it again. If
// the counter hasn't be initialised yet, set it to zero and then perform
// the increment. The fetched value is always parsed as an int to make
// sure the increment will work - this means if a non-int was stored, it
// will be converted first and thus reset the counter to zero.
locache.incr = function(key){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return
var current = parseInt(this.get(key), 10)
if (!current){
current = 0
}
current ++
this.set(key, current)
return current
}
// Exactly the same as the incr function, but with a decrementing value.
locache.decr = function(key){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return
var current = parseInt(this.get(key), 10)
if (!current){
current = 0
}
current --
this.set(key, current)
return current
}
// Given a properties object, in the form of {key: value, key:value} set
// multiple keys.
locache.setMany = function(properties, seconds){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return
// Iterate through all the object properties.
for (var key in properties) {
// Ignore any inherited properties, by making sure they are in
// the given objecct.
if (properties.hasOwnProperty(key)) {
locache.set(key, properties[key], seconds)
}
}
}
// Given an array of keys, return an array of values. If values don't
// exist, null will be in their place.
locache.getMany = function(keys){
var results = []
for (var i=0; i < keys.length; i++){
// To ensure that the correct structure is returned, if
// localStorage isn't supported return an array of null values
// with the correct length.
if (this.supportsLocalStorage){
results.push(this.get(keys[i]))
} else {
results.push(null)
}
}
return results
}
// Given an array of keys, remove all of them from the cache.
locache.removeMany = function(keys){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return
for (var i=0; i < keys.length; i++){
this.remove(keys[i])
}
}
// Delete all stored values from the cache. This method will only remove
// values added to localStorage with the locache prefix in the key.
locache.flush = function(){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return
var length = this.storage.length()
var prefix = this.cachePrefix
// Iteratate through all the keys stored in localStorage - if the key
// starts with the prefix cache prefix, then remove that key.
for (var i=0; i < length; i++) {
var key = this.storage.key(i)
if (key && key.indexOf(prefix) === 0) this.storage.remove(key)
}
}
// Return the number of cache values stored in localStorage. This only
// calculates the values stored by locache.
locache.length = function(){
// If localStorage isn't supported perform a no-op and return zero.
if (!this.supportsLocalStorage) return 0
var c = 0
var length = this.storage.length()
var prefix = this.cachePrefix
for (var i=0; i < length; i++) {
if (this.storage.key(i).indexOf(prefix) === 0) c++
}
return c
}
// A cleanup utility method to remove expired keys. Iterate through all
// the keys stored inlocalStorage. If they key is a locache key (it has
// the prefix) then check to see if the key has expired. If it has,
// remove the key from the cache.
locache.cleanup = function(){
// If localStorage isn't supported perform a no-op.
if (!this.supportsLocalStorage) return
var length = this.storage.length()
var prefix = this.cachePrefix
for (var i=0; i < length; i++) {
var key = this.storage.key(i)
// If the key matches, remove the prefix to get the original key
// and then make use of the normal remove method that will clean
// up the cache value key pair and the cache epiration time key
// pair.
if (key && key.indexOf(prefix) === 0){
var actualKey = key.substring(prefix.length, key.length)
if (this.hasExpired(actualKey)){
this.remove(actualKey)
}
}
}
}
}).call(this);