-
Notifications
You must be signed in to change notification settings - Fork 156
/
angular-cache.js
774 lines (703 loc) · 32.8 KB
/
angular-cache.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/**
* @author Jason Dobry <[email protected]>
* @file angular-cache-<%= pkg.version %>.js
* @version <%= pkg.version %> - [Homepage]{@link http://jmdobry.github.io/angular-cache/}
* @copyright (c) 2013 Jason Dobry <http://jmdobry.github.io/angular-cache>
* @license MIT <https://github.com/jmdobry/angular-cache/blob/master/LICENSE>
*
* @overview angular-cache is a caching system that improves upon the capabilities of the
* $cacheFactory provided by AngularJS.
*/
(function (window, angular, undefined) {
'use strict';
/**
* @module angular-cache
* @desc Provides an $AngularCacheFactoryProvider, which gives you the ability to use an
* $angularCacheFactory. The $angularCacheFactory produces AngularCache objects, which
* the same abilities as the cache objects that come with Angular, except with some added
* functionality.
*/
angular.module('angular-cache', ['ng']);
/**
* @class $AngularCacheFactoryProvider
* @desc Provider for the $angularCacheFactory.
* @see {@link http://docs.angularjs.org/api/ng.$cacheFactory|ng.$cacheFactory}
*/
function $AngularCacheFactoryProvider() {
/**
* @ignore
*/
this.$get = ['$timeout', '$window', function ($timeout, $window) {
var caches = {};
/**
* @method _keySet
* @desc Returns an object of the keys of the given collection.
* @param {Object} collection The collection from which to get the set of keys.
* @returns {Object} A hash of the keys of the given collection.
* @ignore
*/
function _keySet(collection) {
var keySet = {}, key;
for (key in collection) {
if (collection.hasOwnProperty(key)) {
keySet[key] = key;
}
}
return keySet;
}
/**
* @method _keys
* @desc Returns an array of the keys of the given collection.
* @param {Object} collection The collection from which to get the keys.
* @returns {Array} An array of the keys of the given collection.
* @ignore
*/
function _keys(collection) {
var keys = [], key;
for (key in collection) {
if (collection.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
/**
* @class AngularCache
* @desc Instantiated via <code>$angularCacheFactory(cacheId[, options])</code>
* @param {String} cacheId The id of the new cache.
* @param {Object} [options] {{capacity: {Number}, maxAge: {Number}, cacheFlushInterval: {Number} }, aggressiveDelete: {Boolean}, storageMode: {String}}
*/
function AngularCache(cacheId, options) {
var size = 0,
config = angular.extend({}, { id: cacheId }),
data = {},
lruHash = {},
freshEnd = null,
staleEnd = null,
prefix = 'angular-cache.caches.' + cacheId,
cacheDirty = false,
self = this,
storage = null;
options = options || {};
if (!options.hasOwnProperty('aggressiveDelete')) {
options.aggressiveDelete = false;
}
/**
* @method _setTimeoutToRemove
* @desc Removes the item with the given key from this cache after the number of
* milliseconds specified by delay.
* @param {String} key The key of the item to be removed at the end of the timeout.
* @param {Number} delay The delay in milliseconds.
* @private
* @ignore
*/
function _setTimeoutToRemove(key, delay) {
data[key].timeoutId = $timeout(function () {
self.remove(key);
}, delay);
}
/**
* @method _validateNumberOption
* @desc Validates the given number option.
* @param {Number} option The number option to check.
* @param {Function} cb Callback function
* @private
* @ignore
*/
function _validateNumberOption(option, cb) {
if (!angular.isNumber(option)) {
cb('must be a number!', option);
} else if (option < 0) {
cb('must be greater than zero!', option);
} else {
cb(null, option);
}
}
/**
* @method _setCapacity
* @desc Set the capacity for this cache.
* @param {Number} capacity The new capacity for this cache.
* @param {Function} cb Callback function
* @privates
* @ignore
*/
function _setCapacity(capacity, cb) {
if (capacity === Number.MAX_VALUE) {
config.capacity = capacity;
cb(null, config.capacity);
} else {
_validateNumberOption(capacity, function (err, capacity) {
if (err) {
cb(err, capacity);
} else {
config.capacity = capacity;
while (size > config.capacity) {
self.remove(staleEnd.key);
}
cb(null, config.capacity);
}
});
}
}
/**
* @method _setAggressiveDelete
* @desc Set the aggressiveDelete setting for this cache.
* @param {Boolean} aggressiveDelete The new aggressiveDelete for this cache.
* @param {Function} cb Callback function
* @private
* @ignore
*/
function _setAggressiveDelete(aggressiveDelete, cb) {
if (aggressiveDelete === null) {
config.aggressiveDelete = false;
cb(null, config.aggressiveDelete);
} else {
if (aggressiveDelete === true || aggressiveDelete === false) {
config.aggressiveDelete = aggressiveDelete;
cb(null, config.aggressiveDelete);
} else {
cb('must be a boolean!', aggressiveDelete);
}
}
}
/**
* @method _setMaxAge
* @desc Set the maxAge for this cache.
* @param {Number} maxAge The new maxAge for this cache.
* @param {Function} cb Callback function
* @private
* @ignore
*/
function _setMaxAge(maxAge, cb) {
var keys = _keys(data);
if (maxAge === null) {
config.maxAge = maxAge;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (data[key].timeoutId && !data[key].maxAge) {
$timeout.cancel(data[key].timeoutId);
}
}
cb(null, config.maxAge);
} else {
_validateNumberOption(maxAge, function (err, maxAge) {
if (err) {
cb(err, maxAge);
} else {
config.maxAge = maxAge;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!data[key].maxAge) {
if (data[key].timeoutId) {
$timeout.cancel(data[key].timeoutId);
}
var timeRemaining = new Date().getTime() - data[key].timestamp;
if (config.maxAge - timeRemaining > 0 && config.aggressiveDelete) {
_setTimeoutToRemove(key, config.maxAge);
} else {
self.remove(key);
}
}
}
cb(null, config.maxAge);
}
});
}
}
/**
* @method _setCacheFlushInterval
* @desc Set the cacheFlushInterval for this cache.
* @param {Number} cacheFlushInterval The new cacheFlushInterval for this cache.
* @param {Function} cb Callback function
* @private
* @ignore
*/
function _setCacheFlushInterval(cacheFlushInterval, cb) {
if (config.cacheFlushIntervalId) {
clearInterval(config.cacheFlushIntervalId);
delete config.cacheFlushIntervalId;
}
if (cacheFlushInterval === null) {
config.cacheFlushInterval = cacheFlushInterval;
cb(null, config.cacheFlushInterval);
} else {
_validateNumberOption(cacheFlushInterval, function (err, cacheFlushInterval) {
if (err) {
cb(err, cacheFlushInterval);
} else {
config.cacheFlushInterval = cacheFlushInterval;
config.cacheFlushIntervalId = setInterval(function () {
var keys = _keys(data);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (data[key].timeoutId) {
$timeout.cancel(data[key].timeoutId);
}
}
size = 0;
data = {};
lruHash = {};
freshEnd = null;
staleEnd = null;
}, config.cacheFlushInterval);
cb(null, config.cacheFlushInterval);
}
});
}
}
/**
* @method _setStorageMode
* @desc Configure the cache to use localStorage.
* @param {Object} localStorageImpl The localStorage polyfill/replacement to use.
* @param {Object} sessionStorageImpl The sessionStorage polyfill/replacement to use.
* @param {String} storageMode "localStorage"|"sessionStorage"|null
* @param {Function} cb Callback function
* @private
* @ignore
*/
function _setStorageMode(localStorageImpl, sessionStorageImpl, storageMode, cb) {
var keys, i;
if ((config.storageMode === 'localStorage' || config.storageMode === 'sessionStorage') &&
(storageMode !== 'localStorage' && storageMode !== 'sessionStorage')) {
keys = _keys(data);
for (i = 0; i < keys.length; i++) {
storage.removeItem(prefix + '.data.' + keys[i]);
}
storage.removeItem(prefix + '.keys');
} else {
switch (storageMode) {
case 'localStorage':
if (localStorageImpl || $window.localStorage) {
config.storageMode = storageMode;
storage = localStorageImpl || $window.localStorage;
if (!cacheDirty) {
_loadCacheConfig();
} else {
_saveCacheConfig();
keys = _keys(data);
for (i = 0; i < keys.length; i++) {
storage.setItem(prefix + '.data.' + keys[i], angular.toJson(data[keys[i]]));
}
}
}
break;
case 'sessionStorage':
if (sessionStorageImpl || $window.sessionStorage) {
config.storageMode = storageMode;
storage = sessionStorageImpl || $window.sessionStorage;
if (!cacheDirty) {
_loadCacheConfig();
} else {
_saveCacheConfig();
keys = _keys(data);
for (i = 0; i < keys.length; i++) {
storage.setItem(prefix + '.data.' + keys[i], angular.toJson(data[keys[i]]));
}
}
}
break;
default:
config.storageMode = null;
storage = null;
}
}
cb(null, config.storageMode);
}
/**
* @method _setOptions
* @desc Configure this cache with the given options.
* @param {Object} options
* @param {Boolean} strict If true then any existing configuration will be reset to default before
* applying the new options, otherwise only the options specified in the options hash will be altered.
* @private
* @ignore
*/
function _setOptions(options, strict) {
strict = strict || false;
// setup capacity
if (options.capacity || strict) {
_setCapacity(options.capacity ? options.capacity : Number.MAX_VALUE, function (err, capacity) {
if (err) {
throw new Error('capacity: ' + err);
}
});
}
// setup aggressiveDelete
if (options.hasOwnProperty('aggressiveDelete') || strict) {
_setAggressiveDelete(options.hasOwnProperty('aggressiveDelete') ? options.aggressiveDelete : null, function (err, aggressiveDelete) {
if (err) {
throw new Error('aggressiveDelete: ' + err);
}
});
}
if (!options.maxAge && !strict) {
options.maxAge = config.maxAge;
}
// setup maxAge
if (options.maxAge || strict) {
_setMaxAge(options.maxAge ? options.maxAge : null, function (err, maxAge) {
if (err) {
throw new Error('maxAge: ' + err);
}
});
}
// setup cacheFlushInterval
if (options.cacheFlushInterval || strict) {
_setCacheFlushInterval(options.cacheFlushInterval ? options.cacheFlushInterval : null, function (err, cacheFlushInterval) {
if (err) {
throw new Error('cacheFlushInterval: ' + err);
}
});
}
// setup storageMode
if (options.storageMode || strict) {
_setStorageMode(options.localStorageImpl ? options.localStorageImpl : null, options.sessionStorageImpl ? options.sessionStorageImpl : null, options.storageMode ? options.storageMode : null, function (err, storageMode) {
if (err) {
throw new Error('storageMode: ' + err);
}
});
}
cacheDirty = true;
}
/**
* @method refresh
* @desc Makes the `entry` the freshEnd of the LRU linked list.
* @param {Object} entry
* @private
* @ignore
*/
function _refresh(entry) {
if (entry !== freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd === entry) {
staleEnd = entry.n;
}
_link(entry.n, entry.p);
_link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* @method link
* @desc Bidirectionally links two entries of the LRU linked list
* @param {Object} nextEntry
* @param {Object} prevEntry
* @private
* @ignore
*/
function _link(nextEntry, prevEntry) {
if (nextEntry !== prevEntry) {
if (nextEntry) {
nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
}
if (prevEntry) {
prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @method _loadCacheConfig
* @desc If storageMode is set, attempt to load previous cache configuration from localStorage.
* @private
* @ignore
*/
function _loadCacheConfig() {
var keys = angular.fromJson(storage.getItem(prefix + '.keys'));
storage.removeItem(prefix + '.keys');
if (keys && keys.length) {
for (var i = 0; i < keys.length; i++) {
var data = angular.fromJson(storage.getItem(prefix + '.data.' + keys[i])),
maxAge = data.maxAge || config.maxAge;
if (maxAge && ((new Date().getTime() - data.timestamp) > maxAge)) {
storage.removeItem(prefix + '.data.' + keys[i]);
} else {
var options = {
timestamp: data.timestamp
};
if (data.maxAge) {
options.maxAge = data.maxAge;
}
if (data.hasOwnProperty('aggressiveDelete')) {
options.aggressiveDelete = data.aggressiveDelete;
}
self.put(keys[i], data.value);
}
}
_saveCacheConfig();
}
}
/**
* @method _saveCacheConfig
* @desc If storageMode is set, save current keys of cache to localStorage.
* @private
* @ignore
*/
function _saveCacheConfig() {
if (config.storageMode && storage) {
storage.setItem(prefix + '.keys', angular.toJson(_keys(data)));
}
}
/**
* @method AngularCache.put
* @desc Add a key-value pair with timestamp to the cache.
* @param {String} key The identifier for the item to add to the cache.
* @param {*} value The value of the item to add to the cache.
* @param {Object} [options] { maxAge: {Number} }
* @returns {*} value The value of the item added to the cache.
* @privileged
*/
this.put = function (key, value, options) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
if (!angular.isString(key)) {
throw new Error('The key must be a string!');
}
if (options && options.maxAge) {
_validateNumberOption(options.maxAge, function (err, maxAge) {
if (err) {
throw new Error('AngularCache.put(): maxAge: ' + err);
}
});
}
if (options && options.hasOwnProperty('aggressiveDelete')) {
if (options.aggressiveDelete !== true && options.aggressiveDelete !== false) {
throw new Error('AngularCache.put(): aggressiveDelete must be a boolean!');
}
}
_refresh(lruEntry);
if (angular.isUndefined(value)) {
return;
}
if (!(key in data)) {
size++;
}
data[key] = {
value: value
};
if (options && options.hasOwnProperty('aggressiveDelete')) {
data[key].aggressiveDelete = options.aggressiveDelete;
}
data[key].timestamp = (options && options.timestamp) || new Date().getTime();
if ((options && options.maxAge) || config.maxAge) {
if (data[key].timeoutId) {
$timeout.cancel(data[key].timeoutId);
}
if (data[key].aggressiveDelete || (!data[key].hasOwnProperty('aggressiveDelete') && config.aggressiveDelete)) {
_setTimeoutToRemove(key, ((options && options.maxAge) || config.maxAge));
}
}
_saveCacheConfig();
if (config.storageMode) {
storage.setItem(prefix + '.data.' + key, angular.toJson(data[key]));
}
if (size > config.capacity) {
this.remove(staleEnd.key);
}
return value;
};
/**
* @method AngularCache.get
* @desc Retrieve the item from the cache with the specified key.
* @param {String} key The key of the item to retrieve.
* @returns {*} The value of the item in the cache with the specified key.
* @privileged
*/
this.get = function (key) {
var lruEntry = lruHash[key],
maxAge,
aggressiveDelete;
if (!lruEntry) {
return;
}
maxAge = data[key].maxAge || config.maxAge;
aggressiveDelete = data[key].hasOwnProperty('aggressiveDelete') ? data[key].aggressiveDelete : config.aggressiveDelete;
// There is no timeout to delete this item, so we must do it here if it's expired.
if (!aggressiveDelete && maxAge) {
if ((new Date().getTime() - data[key].timestamp) > maxAge) {
// This item is expired so remove it
this.remove(key);
lruEntry = null;
// cache miss
return;
}
}
_refresh(lruEntry);
return data[key].value;
};
/**
* @method AngularCache.remove
* @desc Remove the specified key-value pair from this cache.
* @param {String} key The key of the key-value pair to remove.
* @privileged
*/
this.remove = function (key) {
var lruEntry = lruHash[key];
if (!lruEntry) {
return;
}
if (lruEntry === freshEnd) {
freshEnd = lruEntry.p;
}
if (lruEntry === staleEnd) {
staleEnd = lruEntry.n;
}
_link(lruEntry.n, lruEntry.p);
delete lruHash[key];
delete data[key];
_saveCacheConfig();
if (config.storageMode) {
storage.removeItem(prefix + '.data.' + key);
}
size--;
};
/**
* @method AngularCache.removeAll
* @desc Clear this cache.
* @privileged
*/
this.removeAll = function () {
if (config.storageMode) {
var keys = _keys(data);
for (var i = 0; i < keys.length; i++) {
storage.removeItem(prefix + '.data.' + keys[i]);
}
}
data = {};
size = 0;
lruHash = {};
freshEnd = null;
staleEnd = null;
if (config.storageMode) {
_saveCacheConfig();
}
};
/**
* @method AngularCache.destroy
* @desc Completely destroy this cache.
* @privileged
*/
this.destroy = function () {
clearInterval(config.cacheFlushIntervalId);
if (config.storageMode) {
this.removeAll();
storage.removeItem(prefix + '.keys');
storage.removeItem(prefix);
}
data = null;
config = null;
lruHash = null;
size = null;
freshEnd = null;
staleEnd = null;
prefix = null;
self = null;
delete caches[cacheId];
};
/**
* @method AngularCache.info
* @desc Return an object containing information about this cache.
* @returns {Object} stats Object containing information about this cache.
* @privileged
*/
this.info = function () {
return angular.extend({}, config, { size: size });
};
/**
* @method AngularCache.keySet
* @desc Return the set of the keys of all items currently in this cache.
* @returns {Object} The set of the keys of all items currently in this cache.
* @privileged
*/
this.keySet = function () {
return _keySet(data);
};
/**
* @method AngularCache.keys
* @desc Return an array of the keys of all items currently in this cache..
* @returns {Array} An array of the keys of all items currently in this cache..
* @privileged
*/
this.keys = function () {
return _keys(data);
};
/**
* @method AngularCache.setOptions
* @desc Configure this cache with the given options.
* @param {Object} options
* @param {Boolean} strict If true then any existing configuration will be reset to defaults before
* applying the new options, otherwise only the options specified in the hash will be altered.
* @privileged
*/
this.setOptions = _setOptions;
// Initialize this cache with the default and given options
_setOptions(options, true);
}
/**
* @class AngularCacheFactory
* @param {String} cacheId The id of the new cache.
* @param {Object} [options] { capacity: {Number}, maxAge: {Number} }
* @returns {AngularCache}
*/
function angularCacheFactory(cacheId, options) {
if (cacheId in caches) {
throw new Error('cacheId ' + cacheId + ' taken!');
} else if (!angular.isString(cacheId)) {
throw new Error('cacheId must be a string!');
}
caches[cacheId] = new AngularCache(cacheId, options);
return caches[cacheId];
}
/**
* @method angularCacheFactory.info
* @desc Return an object containing information about all caches of this factory.
* @returns {Object} An object containing information about all caches of this factory.
* @public
*/
angularCacheFactory.info = function () {
var info = {};
var keys = _keys(caches);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
info[key] = caches[key].info();
}
return info;
};
/**
* @method angularCacheFactory.get
* @desc Return the cache with the specified cacheId.
* @param {String} cacheId The id of the desired cache.
* @returns {AngularCache} The cache with the specified cachedId.
* @public
*/
angularCacheFactory.get = function (cacheId) {
return caches[cacheId];
};
/**
* @method angularCacheFactory.keySet
* @desc Return the set of keys associated with all current caches owned by this
* angularCacheFactory.
* @returns {Object} The set of keys associated with all current caches owned by this
* angularCacheFactory.
* @public
*/
angularCacheFactory.keySet = function () {
return _keySet(caches);
};
/**
* @method angularCacheFactory.keys
* @desc Return an array of the keys associated with all current caches owned by this
* angularCacheFactory.
* @returns {Array} An array of the keys associated with all current caches owned by
* this angularCacheFactory.
* @public
*/
angularCacheFactory.keys = function () {
return _keys(caches);
};
return angularCacheFactory;
}];
}
// Register the new provider with Angular.
angular.module('angular-cache').provider('$angularCacheFactory', $AngularCacheFactoryProvider);
})(window, window.angular);