-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache-provider.js
105 lines (97 loc) · 3.07 KB
/
cache-provider.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
/*!
* Version: 1.0
* Started: 22-05-2013
* Updated: 19-07-2018
* Author : paramana (hello AT paramana DOT com)
*
* Initial code taken from CacheProvider of Dustin Diaz (@ded)
* http://www.dustindiaz.com/javascript-cache-provider/
*
*/
define('CacheProvider', [], function() {
'use strict';
// values will be stored here
var CacheProvider = {},
_cache = {};
CacheProvider = {
/**
* {String} k - the key
* {Boolean} local - get this from local storage?
* {Boolean} o - is the value you put in local storage an object?
*/
getAll: function(local) {
if (local && CacheProvider.hasLocalStorage)
return localStorage || undefined;
else
return _cache || undefined;
},
/**
* {String} k - the key
* {Boolean} local - get this from local storage?
* {Boolean} o - is the value you put in local storage an object?
*/
get: function(k, local, o) {
if (local && CacheProvider.hasLocalStorage) {
var action = o ? 'getObject' : 'getItem';
return localStorage[action](k) || undefined;
}
else {
return _cache[k] || undefined;
}
},
/**
* {String} k - the key
* {Object} v - any kind of value you want to store
* however only objects and strings are allowed in local storage
* {Boolean} local - put this in local storage
*/
set: function(k, v, local) {
if (local && CacheProvider.hasLocalStorage) {
try {
localStorage.setItem(k, v);
}
catch (ex) {
if (ex.name == 'QUOTA_EXCEEDED_ERR') {
// developer needs to figure out what to start invalidating
throw v;
return;
}
}
}
else {
// put in our local object
_cache[k] = v;
}
// return our newly cached item
return v;
},
/**
* {String} k - the key
* {Boolean} local - put this in local storage
*/
clear: function(k, local) {
if (local && CacheProvider.hasLocalStorage)
localStorage.removeItem(k);
// delete in both caches - doesn't hurt.
delete _cache[k];
},
/**
* Empty the cache
*
* {Boolean} all - if true clears everything and the variables cache
*/
empty: function(all) {
if (CacheProvider.hasLocalStorage)
localStorage.clear();
if (all)
_cache = {};
}
};
try {
CacheProvider.hasLocalStorage = ('localStorage' in window) && window['localStorage'] !== null && typeof localStorage !== 'undefined';
}
catch (ex) {
CacheProvider.hasLocalStorage = false;
}
return CacheProvider;
});