-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cache.js
55 lines (46 loc) · 1.23 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
/**
* Caching interface for Hapi
*/
const client = require('redis');
class Cache {
/**
* Set up general cache
* @return {void}
*/
constructor (config) {
this.config = config;
this.cacheClient = client.createClient(config.redisUrl);
}
/**
* Set a value to cache
* @param {String} key Key to store value to
* @param {String} value Value to store
* @param {Number} expiresIn Milliseconds after which the cached value gets deleted
* @param {Function} callback Callback
* @return {void}
*/
set (key, value, expiresIn = this.config.expiresIn, callback = () => {}) {
value = JSON.stringify(value);
this.cacheClient.set(key, value, 'PX', expiresIn, (error) => {
if (error) {
throw error;
}
callback && callback();
});
}
/**
* Get a specific value from the store
* @param {String} key Key to get
* @param {Function} callback Function to fire after cached value was retrieved
* @return {void}
*/
get (key, callback) {
this.cacheClient.get(key, (error, value) => {
try {
value = JSON.parse(value);
} catch (error) {}
callback && callback(error, value);
});
}
}
module.exports = Cache;