1 | "use strict";
|
2 |
|
3 | function calculateNextResetTime(windowMs) {
|
4 | const d = new Date();
|
5 | d.setMilliseconds(d.getMilliseconds() + windowMs);
|
6 | return d;
|
7 | }
|
8 |
|
9 | function MemoryStore(windowMs) {
|
10 | let hits = {};
|
11 | let resetTime = calculateNextResetTime(windowMs);
|
12 |
|
13 | this.incr = function (key, cb) {
|
14 | if (hits[key]) {
|
15 | hits[key]++;
|
16 | } else {
|
17 | hits[key] = 1;
|
18 | }
|
19 |
|
20 | cb(null, hits[key], resetTime);
|
21 | };
|
22 |
|
23 | this.decrement = function (key) {
|
24 | if (hits[key]) {
|
25 | hits[key]--;
|
26 | }
|
27 | };
|
28 |
|
29 |
|
30 | this.resetAll = function () {
|
31 | hits = {};
|
32 | resetTime = calculateNextResetTime(windowMs);
|
33 | };
|
34 |
|
35 |
|
36 | this.resetKey = function (key) {
|
37 | delete hits[key];
|
38 | };
|
39 |
|
40 |
|
41 | const interval = setInterval(this.resetAll, windowMs);
|
42 | if (interval.unref) {
|
43 | interval.unref();
|
44 | }
|
45 | }
|
46 |
|
47 | module.exports = MemoryStore;
|