-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (46 loc) · 1.24 KB
/
index.js
File metadata and controls
51 lines (46 loc) · 1.24 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
function rejectWithMessage(error) {
return Promise.reject(error.message);
}
const store = (() => {
function isLocalStorageValid() {
try {
return typeof localStorage !== 'undefined' &&
('setItem' in localStorage) &&
typeof localStorage.setItem === 'function';
} catch (e) {
return false;
}
}
if (isLocalStorageValid()) {
return localStorage;
}
return {
db: {},
setItem(key, value) {
this.db[key] = value;
},
getItem(key, value) {
const value = this.db[key];
if (value === undefined) {
// emulate localStorage
return null;
}
return value
}
};
})();
export default (key, replacer, reviver) => ({
load() {
return new Promise((resolve) => {
const jsonState = store.getItem(key);
resolve(JSON.parse(jsonState, reviver) || {});
}).catch(rejectWithMessage);
},
save(state) {
return new Promise((resolve) => {
const jsonState = JSON.stringify(state, replacer);
store.setItem(key, jsonState);
resolve();
}).catch(rejectWithMessage);
}
});