-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.js
64 lines (57 loc) · 1.47 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
59
60
61
62
63
64
const NodeCache = require('node-cache');
const myCache = new NodeCache();
const md5 = require('md5');
/**
* Cache to store key value pairs, retrieve values by key, and get current list of keys
* Provides a default TTL in seconds as TTL_SECS_DEFAULT
*/
class Cache {
static instance() {
if (!this.INSTANCE) {
this.INSTANCE = new Cache();
}
return this.INSTANCE;
}
/**
* Get cached value for key
* @param {String} key Key to retrieve
* @param {Function} callback Callback function
* @returns Value for key, or undefined if key is not found
*/
get(key, callback) {
return myCache.get(md5(key), (err, data) => {
if (callback) {
callback(err, data);
}
});
}
/**
* Set cached value
* @param {String} key key for cached value
* @param {any} val Value to cache
* @param {number} ttl Time-to-live; expires value after value is exceeded
* @param {Function} callback Callback function
* @returns true if successful, else false
*/
set(key, val, ttl, callback) {
return myCache.set(md5(key), val, ttl, (err, success) => {
if (callback) {
callback(err, success);
}
});
}
/**
* Gets array of currently saved keys
* @param {Function} callback Callback function
* @returns Array of keys
*/
keys(callback) {
return myCache.keys((err, keys) => {
if (callback) {
callback(err, keys);
}
});
}
}
Cache.TTL_SECS_DEFAULT = 600;
module.exports = Cache;