UNPKG

958 BJavaScriptView Raw
1"use strict";
2
3function calculateNextResetTime(windowMs) {
4 const d = new Date();
5 d.setMilliseconds(d.getMilliseconds() + windowMs);
6 return d;
7}
8
9function 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 // export an API to allow hits all IPs to be reset
30 this.resetAll = function () {
31 hits = {};
32 resetTime = calculateNextResetTime(windowMs);
33 };
34
35 // export an API to allow hits from one IP to be reset
36 this.resetKey = function (key) {
37 delete hits[key];
38 };
39
40 // simply reset ALL hits every windowMs
41 const interval = setInterval(this.resetAll, windowMs);
42 if (interval.unref) {
43 interval.unref();
44 }
45}
46
47module.exports = MemoryStore;