-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
cache.js
40 lines (34 loc) · 1.14 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
/**
* Simple in-memory cache
*/
class Cache {
constructor(name, expiration=24) {
this.items = [];
this.name = name;
this.expiration = expiration; // expiration in hours
}
exists(id) {
return this.items.find(cache => cache.id === id && !this.isExpired(cache.lastUpdate));
}
isExpired(timestamp) {
return (new Date().valueOf() - timestamp) / (1000 * 60 * 60 * this.expiration) >= 1;
}
add(id, data) {
const isArray = Array.isArray(data);
const isString = typeof data === "string" || data instanceof String;
const isObject = typeof data === "object";
if (!data || ((isArray || isString) && !data.length) || (!isArray && !isString && !isObject)) return null;
console.log(`[CACHE ${this.name}] Adding to the Cache (ID: ${id}): ${data.length} items.`);
const index = this.items.find(cache => cache.id === id);
if (index) {
console.log(`[CACHE ${this.name}] Removing expired entry from cache`);
this.items = this.items.filter(cache => cache.id !== id);
}
this.items.push({
id: id,
lastUpdate: new Date().valueOf(),
data: data,
});
}
}
module.exports = Cache;