forked from leancloud/javascript-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.js
More file actions
37 lines (33 loc) · 908 Bytes
/
Copy pathcache.js
File metadata and controls
37 lines (33 loc) · 908 Bytes
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
const storage = require('./localstorage');
const AV = require('./av');
const removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);
const getCacheData = (cacheData, key) => {
try {
cacheData = JSON.parse(cacheData);
} catch (e) {
return null;
}
if (cacheData) {
const expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();
if (!expired) {
return cacheData.value;
}
return removeAsync(key).then(() => null);
}
return null;
};
exports.getAsync = (key) => {
key = `AV/${AV.applicationId}/${key}`;
return storage.getItemAsync(key)
.then(cache => getCacheData(cache, key));
};
exports.setAsync = (key, value, ttl) => {
const cache = { value };
if (typeof ttl === 'number') {
cache.expiredAt = Date.now() + ttl;
}
return storage.setItemAsync(
`AV/${AV.applicationId}/${key}`,
JSON.stringify(cache)
);
};