| 6 | } |
| 7 | |
| 8 | export class MemoryStore implements Store { |
| 9 | hits = {} |
| 10 | resetTime: Date |
| 11 | |
| 12 | constructor(private windowMs: number) { |
| 13 | this.resetTime = this.calculateNextResetTime(windowMs) |
| 14 | |
| 15 | const interval = setInterval(this.resetAll, windowMs) |
| 16 | if (interval.unref) interval.unref() |
| 17 | } |
| 18 | |
| 19 | incr = async (key: string, callback: (error: Error | null, hits: number, resetTime: Date) => void) => { |
| 20 | if (this.hits[key]) this.hits[key]++ |
| 21 | else this.hits[key] = 1 |
| 22 | |
| 23 | callback(null, this.hits[key], this.resetTime) |
| 24 | } |
| 25 | |
| 26 | decrement(key: string) { |
| 27 | if (this.hits[key]) this.hits[key]-- |
| 28 | } |
| 29 | |
| 30 | resetAll = () => { |
| 31 | this.hits = {} |
| 32 | this.resetTime = this.calculateNextResetTime(this.windowMs) |
| 33 | } |
| 34 | |
| 35 | resetKey(key: string) { |
| 36 | delete this.hits[key] |
| 37 | } |
| 38 | |
| 39 | calculateNextResetTime(windowMs) { |
| 40 | const nextResetDate = new Date() |
| 41 | nextResetDate.setMilliseconds(nextResetDate.getMilliseconds() + windowMs) |
| 42 | return nextResetDate |
| 43 | } |
| 44 | } |
nothing calls this directly
no test coverage detected