Skip to content

Commit f502b74

Browse files
friebetilljmcdo29
authored andcommitted
feat: Add throwThrottlingException method
Resolves #531. I am unsure about: - the name of the `throwException` vs `throwThrottlerException` vs `throwThrottlingException` method. In the end I decided to use `throwThrottlingException` because it's more precise than `throwException` and `throwThrottlerException` sounds like one is always throwing `ThrottlerException`, which is not the case when overriding the method (but not a strong opinion). - the line with "eslint-disable-next-line...". I added `context` as a parameter because of your comment @jmcdo29, but since I see no point in using `context` for the default case, I had to disable eslint for the line. I don't know if this is against any practices of this project.
1 parent d1803bd commit f502b74

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/throttler.guard.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ export class ThrottlerGuard implements CanActivate {
8080
// Throw an error when the user reached their limit.
8181
if (ttls.length >= limit) {
8282
res.header('Retry-After', nearestExpiryTime);
83-
throw new ThrottlerException(this.errorMessage);
83+
this.throwThrottlingException(context);
8484
}
8585

8686
res.header(`${this.headerPrefix}-Limit`, limit);
@@ -97,9 +97,10 @@ export class ThrottlerGuard implements CanActivate {
9797
return req.ip;
9898
}
9999

100-
protected getRequestResponse(
101-
context: ExecutionContext,
102-
): { req: Record<string, any>; res: Record<string, any> } {
100+
protected getRequestResponse(context: ExecutionContext): {
101+
req: Record<string, any>;
102+
res: Record<string, any>;
103+
} {
103104
const http = context.switchToHttp();
104105
return { req: http.getRequest(), res: http.getResponse() };
105106
}
@@ -112,4 +113,16 @@ export class ThrottlerGuard implements CanActivate {
112113
const prefix = `${context.getClass().name}-${context.getHandler().name}`;
113114
return md5(`${prefix}-${suffix}`);
114115
}
116+
117+
/**
118+
* Throws an exception for the event that the rate limit has been exceeded.
119+
*
120+
* The context parameter allows to access the context when overwriting
121+
* the method.
122+
* @throws ThrottlerException
123+
*/
124+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
125+
protected throwThrottlingException(context: ExecutionContext): void {
126+
throw new ThrottlerException(this.errorMessage);
127+
}
115128
}

0 commit comments

Comments
 (0)