Skip to content

Commit

Permalink
fix(interface): fixes the storage interface to be async
Browse files Browse the repository at this point in the history
The ThrottlerStorage interface now expects `getRecord` and `addRecord` to return promises, allowing
the methods to be called with `await`.
  • Loading branch information
jmcdo29 committed Jun 7, 2020
1 parent 5d45b5b commit f7565d9
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/throttler-storage.interface.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export interface ThrottlerStorage {
getRecord(key: string): number[];
addRecord(key: string, ttl: number): void;
getRecord(key: string): Promise<number[]>;
addRecord(key: string, ttl: number): Promise<void>;
}

export const ThrottlerStorage = Symbol('ThrottlerStorage');
4 changes: 2 additions & 2 deletions src/throttler.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}
}
4 changes: 2 additions & 2 deletions src/throttler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { ThrottlerStorage } from './throttler-storage.interface';
export class ThrottlerStorageService implements ThrottlerStorage {
storage: Record<string, number[]> = {};

getRecord(key: string): number[] {
async getRecord(key: string): Promise<number[]> {
return this.storage[key] || [];
}

addRecord(key: string, ttl: number): void {
async addRecord(key: string, ttl: number): Promise<void> {
const ttlMilliseconds = ttl * 1000;
if (!this.storage[key]) {
this.storage[key] = [];
Expand Down

0 comments on commit f7565d9

Please sign in to comment.