-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache-helper.js
45 lines (41 loc) · 1.41 KB
/
cache-helper.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
'use strict';
import redisJson from 'redis-store-json';
import redis from 'redis';
const client = redis.createClient (
{host: 'redis-server', port: 6379}
);
//const client = redis.createClient ({port: 6379});
redisJson.use(client);
const KEY_TTL_SECONDS = 300;
class CacheHelper {
constructor() {
console.log('cachehelper ctor called');
}
addDataToCache(keyToAdd, dataToAdd) {
redisJson.set(keyToAdd, dataToAdd) // set a new JSON key
.then(() => {
client.expire(keyToAdd, KEY_TTL_SECONDS);
console.log("succefuly set data" + keyToAdd);
})
.catch(() => {
console.log("error when set data");
})
}
/*if key exists - then callbackExists will be called , else callbackNotExists*/
checkDataByKey(keyToCheck, callbackExists, callbackNotExists) {
client.exists(keyToCheck, function (err, reply) {
if (reply === 1) {
console.log('exists in cache');
redisJson.getJSON(keyToCheck)
.then(data => callbackExists(data))
.catch(err => console.error(err))
} else {
console.log('Does not exist in cache. Will be taken from outside');
callbackNotExists(keyToCheck);
}
})
}
}
export default {
CacheHelper
};