-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (62 loc) · 1.54 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
function requireSafely(module) {
try {
return require(module);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
return null;
} else {
throw e;
}
}
}
function getWrapper(...args) {
const memjs = requireSafely('memjs');
if (memjs) {
const MemjsWrapper = require('./lib/memjs-wrapper');
return new MemjsWrapper(memjs, ...args);
}
const Memcached = requireSafely('memcached');
if (Memcached) {
const MemcachedWrapper = require('./lib/memcached-wrapper');
return new MemcachedWrapper(Memcached, ...args);
}
throw new Error("Please add either memjs or memcached to your application's dependencies.")
}
class MemcachedCache {
constructor({servers, expiration, cacheKey} = {}) {
this.client = getWrapper({
servers,
expires: expiration || 5 * 60
});
this.cacheKey = cacheKey || ((path) => path)
}
fetch(path, request) {
const key = this.cacheKey(path, request);
return new Promise((resolve, reject) => {
this.client.get(key, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
put(path, body, response) {
const key = this.cacheKey(path, response.req);
return new Promise((resolve, reject) => {
if (response.statusCode !== 200) {
resolve();
return;
}
this.client.set(key, body, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
}
module.exports = MemcachedCache;