From f7565d9029baf4d7687f0913046f555d17cde44b Mon Sep 17 00:00:00 2001 From: Jay McDoniel Date: Sat, 6 Jun 2020 23:16:10 -0700 Subject: [PATCH] fix(interface): fixes the storage interface to be async The ThrottlerStorage interface now expects `getRecord` and `addRecord` to return promises, allowing the methods to be called with `await`. --- src/throttler-storage.interface.ts | 4 ++-- src/throttler.guard.ts | 4 ++-- src/throttler.service.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/throttler-storage.interface.ts b/src/throttler-storage.interface.ts index 091443ef..c9691f90 100644 --- a/src/throttler-storage.interface.ts +++ b/src/throttler-storage.interface.ts @@ -1,6 +1,6 @@ export interface ThrottlerStorage { - getRecord(key: string): number[]; - addRecord(key: string, ttl: number): void; + getRecord(key: string): Promise; + addRecord(key: string, ttl: number): Promise; } export const ThrottlerStorage = Symbol('ThrottlerStorage'); diff --git a/src/throttler.guard.ts b/src/throttler.guard.ts index 1c54d508..b2fe922e 100644 --- a/src/throttler.guard.ts +++ b/src/throttler.guard.ts @@ -47,7 +47,7 @@ export class ThrottlerGuard implements CanActivate { const req = context.switchToHttp().getRequest(); const res = context.switchToHttp().getResponse(); const key = md5(`${req.ip}-${classRef.name}-${handler.name}`); - const ttls = this.storageService.getRecord(key); + const ttls = await this.storageService.getRecord(key); const nearestExpiryTime = ttls.length > 0 ? Math.ceil((ttls[0] - Date.now()) / 1000) : 0; // Throw an error when the user reached their limit. @@ -62,7 +62,7 @@ export class ThrottlerGuard implements CanActivate { res.header(`${headerPrefix}-Remaining`, Math.max(0, limit - (ttls.length + 1))); res.header(`${headerPrefix}-Reset`, nearestExpiryTime); - this.storageService.addRecord(key, ttl); + await this.storageService.addRecord(key, ttl); return true; } } diff --git a/src/throttler.service.ts b/src/throttler.service.ts index 3e08f82c..4bb644d1 100644 --- a/src/throttler.service.ts +++ b/src/throttler.service.ts @@ -5,11 +5,11 @@ import { ThrottlerStorage } from './throttler-storage.interface'; export class ThrottlerStorageService implements ThrottlerStorage { storage: Record = {}; - getRecord(key: string): number[] { + async getRecord(key: string): Promise { return this.storage[key] || []; } - addRecord(key: string, ttl: number): void { + async addRecord(key: string, ttl: number): Promise { const ttlMilliseconds = ttl * 1000; if (!this.storage[key]) { this.storage[key] = [];