-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
111 lines (94 loc) · 3.03 KB
/
storage.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
'use strict';
function Storage(name, type) {
this.storageType = type || 'sessionStorage';
this.storageEnabled = false;
this.defaultValue = {};
this.storageName = name || '';
this.keyIsValid = false;
this.initialize();
}
Storage.prototype = {
constructor: Storage,
initialize: function(){
this.storageEnabled = this.storageAvailable();
this.keyIsValid = this.hasKeyInStorageDB();
if(this.storageEnabled && !this.keyIsValid){
window[this.storageType].setItem(this.storageName, JSON.stringify({}))
}
},
storageAvailable: function () {
if (this.storageType in window) {
try {
window[this.storageType].setItem('storagetemp', 'storagetemp');
window[this.storageType].removeItem('storagetemp');
return true;
} catch (err) {
// Exception iOS5 private mode
// some browsers throw error when touching localStorage & cookies are disabled
return false;
}
}
return false;
},
setStorageValue: function (groups) {
if (this.keyIsValid && ({}).toString.call(groups) === '[object Array]') {
var db = this.getStorageDB();
groups.forEach(function (group) {
for (var key in group) {
db[key] = group[key];
}
})
window[this.storageType].setItem(this.storageName, JSON.stringify(db));
}
},
getStorageValue: function () {
if (this.keyIsValid) {
var storageVals = {},
dB = this.getStorageDB();
this.requestedKeys.apply([], arguments).filter(function(key){
return key in dB;
}).forEach(function(key) {
storageVals[key] = dB[key];
});
return Object.keys(storageVals).length === 1
? storageVals[Object.keys(storageVals).join()]
: storageVals;
}
return this.defaultValue;
},
hasKeyInStorageDB: function () {
if (!this.storageAvailable || !(this.storageName in window[this.storageType])) {
return false;
}
return true;
},
getStorageDB: function () {
if (this.keyIsValid) {
return JSON.parse(window[this.storageType].getItem(this.storageName));
}
return this.defaultValue;
},
removeStorageValue: function () {
if (this.keyIsValid) {
var dB = this.getStorageDB();
this.requestedKeys.apply([], arguments).forEach(function(key){
delete dB[key];
})
window[this.storageType].setItem(this.storageName, JSON.stringify(dB));
}
return this.getStorageDB();
},
getStorageLength: function() {
return Object.keys(this.getStorageDB()).length;
},
clearStorageDB: function() {
window[this.storageType].setItem(this.storageName, '');
},
deleteStorageDB: function() {
window[this.storageType].removeItem(this.storageName);
},
requestedKeys: function() {
return [].concat([], [].slice.apply(arguments));
}
};
module.exports = Storage;