-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
41 lines (34 loc) · 976 Bytes
/
index.js
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
function serializeArguments (obj) {
return Array
.from(obj)
.map(val => JSON.stringify(val))
.join('-')
}
function factory (type = 'lru', options = {}) {
const CacheDriver = require(`./lib/${type}CacheDriver`)
const cacheDriver = new CacheDriver(options)
const Cache = {
options,
cacheDriver
}
Cache.remember = function rememberFunc (key, func, timeout) {
return function () {
return new Promise((resolve, reject) => {
const cacheKey = `${key}-${serializeArguments(arguments)}`
cacheDriver.get(cacheKey).then((cacheData) => {
if (cacheData.invalid()) {
func.apply(this, arguments).then((data) => {
// cache data
cacheDriver.set(cacheKey, data, timeout)
resolve(data)
}).catch(err => reject(err))
} else {
resolve(cacheData.data)
}
})
})
}
}
return Cache
}
module.exports = factory