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
44 lines (38 loc) · 1.06 KB
/
Copy pathcache.js
File metadata and controls
44 lines (38 loc) · 1.06 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
'use strict';
/**
* 每位工程师都有保持代码优雅的义务
* Each engineer has a duty to keep the code elegant
**/
var storage = require('./localstorage');
var AV = require('./av');
var removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);
var getCacheData = function getCacheData(cacheData, key) {
try {
cacheData = JSON.parse(cacheData);
} catch (e) {
return null;
}
if (cacheData) {
var expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();
if (!expired) {
return cacheData.value;
}
return removeAsync(key).then(function () {
return null;
});
}
return null;
};
exports.getAsync = function (key) {
key = AV.applicationId + '/' + key;
return storage.getItemAsync(key).then(function (cache) {
return getCacheData(cache, key);
});
};
exports.setAsync = function (key, value, ttl) {
var cache = { value: value };
if (typeof ttl === 'number') {
cache.expiredAt = Date.now() + ttl;
}
return storage.setItemAsync(AV.applicationId + '/' + key, JSON.stringify(cache));
};