-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
58 lines (48 loc) · 1.27 KB
/
cache.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const l = module.exports
const defaultTTL = 10 // in sec
let cache
l.initialize = () => {
if (cache) return Promise.resolve()
const cacheManager = require('cache-manager'),
redisStore = require('cache-manager-redis-store'),
config = require('./config')
cache = cacheManager.caching({
store: redisStore,
host: config.redis.host,
db: 0,
ttl: 600
})
}
l.close = () => {
cache.store.getClient().quit()
cache = null
return Promise.resolve()
}
l.set = (key, val, ttl) => {
return new Promise(function (resolve, reject) {
const json = val.toObject ? val.toObject() : val
cache.set(key, json, ttl || defaultTTL, function (err) {
if (err) return reject(err)
resolve(val)
})
})
}
l.get = (key, Model) => {
return new Promise(function (resolve, reject) {
cache.get(key, function (err, val) {
if (err) return reject(err)
if (val && Model) {
val = Model.hydrate(val)
}
resolve(val)
})
})
}
l.del = (key) => {
return new Promise(function (resolve, reject) {
cache.del(key, function (err) {
if (err) return reject(err)
resolve()
})
})
}