-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
80 lines (64 loc) · 1.8 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
const redis = require('redis');
const FIVE_MINUTES = 5 * 60;
class RedisCache {
constructor(options) {
let client = this.client = redis.createClient({
host: options.host,
port: options.port
});
this.expiration = options.expiration || FIVE_MINUTES;
this.connected = false;
this.cacheKey = typeof options.cacheKey === 'function' ?
options.cacheKey : (path) => path;
client.on('error', error => {
this.ui.writeLine(`redis error; err=${error}`);
});
this.client.on('connect', () => {
this.connected = true;
this.ui.writeLine('redis connected');
});
this.client.on('end', () => {
this.connected = false;
this.ui.writeLine('redis disconnected');
});
}
fetch(path, request) {
if (!this.connected) { return; }
let key = this.cacheKey(path, request);
return new Promise((res, rej) => {
this.client.get(key, (err, reply) => {
if (err) {
rej(err);
} else {
res(reply);
}
});
});
}
put(path, body, response) {
if (!this.connected) { return; }
let request = response && response.req;
let key = this.cacheKey(path, request);
return new Promise((res, rej) => {
let statusCode = response && response.statusCode;
let statusCodeStr = statusCode && (statusCode + '');
if (statusCodeStr && statusCodeStr.length &&
(statusCodeStr.charAt(0) === '4' || statusCodeStr.charAt(0) === '5' || statusCodeStr.charAt(0) === '3')) {
res();
return;
}
this.client.multi()
.set(key, body)
.expire(path, this.expiration)
.exec(err => {
if (err) {
rej(err);
} else {
res();
}
});
});
}
}
module.exports = RedisCache;