-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcache.js
More file actions
59 lines (55 loc) · 1.58 KB
/
cache.js
File metadata and controls
59 lines (55 loc) · 1.58 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
52
53
54
55
56
57
58
59
const assert = require('assert');
const helper = require('think-helper');
const Debounce = require('think-debounce');
const debounceInstance = new Debounce();
/**
* cache manage
* can not be defined a arrow function, because has `this` in it.
* @param {String} name
* @param {Mixed} value
* @param {String|Object} config
*/
function thinkCache(name, value, config) {
assert(name && helper.isString(name), 'cache.name must be a string');
if (config) {
config = helper.parseAdapterConfig(this.config('cache'), config);
} else {
config = helper.parseAdapterConfig(this.config('cache'));
}
const Handle = config.handle;
assert(helper.isFunction(Handle), 'cache.handle must be a function');
delete config.handle;
const instance = new Handle(config);
// delete cache
if (value === null) {
return Promise.resolve(instance.delete(name));
}
// get cache
if (value === undefined) {
return debounceInstance.debounce(name, () => {
return instance.get(name);
});
}
// get cache when value is function
if (helper.isFunction(value)) {
return debounceInstance.debounce(name, () => {
let cacheData;
return instance.get(name).then(data => {
if (data === undefined) {
return value(name);
}
cacheData = data;
}).then(data => {
if (data !== undefined) {
cacheData = data;
return instance.set(name, data);
}
}).then(() => {
return cacheData;
});
});
}
// set cache
return Promise.resolve(instance.set(name, value));
}
module.exports = thinkCache;