forked from parse-community/parse-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInMemoryCache.js
More file actions
61 lines (49 loc) · 1.07 KB
/
InMemoryCache.js
File metadata and controls
61 lines (49 loc) · 1.07 KB
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
const DEFAULT_CACHE_TTL = 5 * 1000;
export class InMemoryCache {
constructor({ ttl = DEFAULT_CACHE_TTL }) {
this.ttl = ttl;
this.cache = Object.create(null);
}
get(key) {
const record = this.cache[key];
if (record == null) {
return null;
}
// Has Record and isnt expired
if (isNaN(record.expire) || record.expire >= Date.now()) {
return record.value;
}
// Record has expired
delete this.cache[key];
return null;
}
put(key, value, ttl = this.ttl) {
if (ttl < 0 || isNaN(ttl)) {
ttl = NaN;
}
var record = {
value: value,
expire: ttl + Date.now(),
};
if (!isNaN(record.expire)) {
record.timeout = setTimeout(() => {
this.del(key);
}, ttl);
}
this.cache[key] = record;
}
del(key) {
var record = this.cache[key];
if (record == null) {
return;
}
if (record.timeout) {
clearTimeout(record.timeout);
}
delete this.cache[key];
}
clear() {
this.cache = Object.create(null);
}
}
export default InMemoryCache;