-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.js
More file actions
73 lines (62 loc) · 1.59 KB
/
cache.js
File metadata and controls
73 lines (62 loc) · 1.59 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
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Created by yss on 6/11/17.
*/
'use strict';
class Cache extends Map {
/**
* memory cache
* @param {number} [ttl] time to live
*/
constructor (ttl) {
super ();
this._ttl = ttl && typeof ttl === 'number' ? ttl : 5;
this._timerMap = new Map();
}
/**
* set cache with expired time
*
* @param {*} key
* @param {*} value
* @param {number} [ttl=5] time to live, and the unit is second
*/
set (key, value, ttl) {
// ignore duplicate setting
if (this.has(key)) {
return;
}
super.set(key, value);
// remove it after timeout
const timer = setTimeout(this.delete.bind(this, key), (typeof ttl === 'number' ? ttl : this._ttl) * 1000);
// and prevent the setTimeout from stop the server shutdown on node environment
timer.unref && timer.unref();
this._timerMap.set(key, timer);
}
/**
* change the default ttl
* or one key's ttl
*
* @param {number} ttl
* @param {*} [key]
*/
setTtl (ttl, key) {
if (typeof ttl !== 'number') {
return;
}
if (!key) {
this._ttl = ttl;
} else if (this.has(key)) {
let value = this.get(key);
this.delete(key);
this.set(key, value, ttl);
}
}
'delete' (key) {
super.delete(key);
const timerMap = this._timerMap;
if (timerMap.has(key)) {
clearTimeout(timerMap.get(key));
timerMap.delete(key);
}
}
}
module.exports = Cache;