/
Storage.ts
58 lines (47 loc) · 1.57 KB
/
Storage.ts
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
/// <reference path="../typings/cocos-creator.d.ts" />
/**
* We do not assign 'storage' to window.localStorage immediatelly for React
* Native compatibility. window.localStorage is not present when this module is
* loaded.
*/
let storage: any;
function getStorage(): Storage {
if (!storage) {
try {
storage = (typeof (cc) !== 'undefined' && cc.sys && cc.sys.localStorage)
? cc.sys.localStorage // compatibility with cocos creator
: window.localStorage; // RN does have window object at this point, but localStorage is not defined
} catch (e) {
// ignore error
}
}
if (!storage) {
// mock localStorage if not available (Node.js or RN environment)
storage = {
cache: {},
setItem: function (key, value) { this.cache[key] = value; },
getItem: function (key) { this.cache[key]; },
removeItem: function (key) { delete this.cache[key]; },
};
}
return storage;
}
export function setItem(key: string, value: string) {
getStorage().setItem(key, value);
}
export function removeItem(key: string) {
getStorage().removeItem(key);
}
export function getItem(key: string, callback: Function) {
const value: any = getStorage().getItem(key);
if (
typeof (Promise) === 'undefined' || // old browsers
!(value instanceof Promise)
) {
// browser has synchronous return
callback(value);
} else {
// react-native is asynchronous
value.then((id) => callback(id));
}
}