-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cache.js
87 lines (78 loc) · 2.37 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const persistentCache = require('persistent-cache');
const cast = require('localcast')();
const { bold, magenta, yellow, green, gray, blue, cyan } = require('./Logging');
const cacheSymbol = Symbol('cache');
const genId = query => JSON.stringify(query)
.replace(/\{|\}|"/g, '')
.replace(/:/g, '=')
.replace(/\//g, '_');
class Cache {
constructor({ base = 'cache', name = 'cache', logging = true, localcast = false } = {}) {
Object.assign(this, { base, name, logging, localcast });
this[cacheSymbol] = persistentCache({ base, name });
}
log(operation, id) {
if (this.logging) {
const { base, name } = this;
const path = base
.replace(/cache\//g, '')
.replace(/\//g, ' ');
const action = `${cyan('[Cache]')} ${gray(operation)}`;
let cacheName;
let params;
if (typeof id === 'string') {
cacheName = blue(`[${path} ${name}]`);
params = green(id);
} else {
cacheName = bold(magenta(`[${path}]`));
params = `${bold(name)} { ${Object.entries(id).map(([key, value]) => {
if (typeof value === 'number') return `${key}: ${yellow(value)}`;
if (typeof value === 'string') return `${key}: ${green(`'${value}'`)}`;
return `${key}: ${value}`;
}).join(', ')} }`;
}
if (this.localcast) {
cast.emit('Cache', JSON.stringify({ action, cacheName, params }));
} else {
console.log(`${action} ${cacheName} ${params}`);
}
}
}
ids() {
return new Promise((resolve, reject) => {
this[cacheSymbol].keys((err, keys) => {
if (err) reject(new Error(err));
resolve(keys);
});
});
}
has(key) {
return new Promise((resolve, reject) => {
this.ids()
.then((keys) => {
const hasKey = keys.includes(genId(key));
resolve(hasKey);
})
.catch(err => reject(err));
});
}
get(key) {
return new Promise((resolve, reject) => {
this[cacheSymbol].get(genId(key), (err, result) => {
if (err) reject(err);
if (result) this.log('Get', key);
resolve(result);
});
});
}
put(key, object) {
return new Promise((resolve, reject) => {
this[cacheSymbol].put(genId(key), object, (err, result) => {
if (err) reject(err);
this.log('Put', key);
resolve(result);
});
});
}
}
module.exports = Cache;