Skip to content

Commit c8336ab

Browse files
committed
docs: update websockets throttler guard example
1 parent d940f58 commit c8336ab

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

content/security/rate-limiting.md

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,14 +132,29 @@ This module can work with websockets, but it requires some class extension. You
132132
```typescript
133133
@Injectable()
134134
export class WsThrottlerGuard extends ThrottlerGuard {
135-
async handleRequest(context: ExecutionContext, limit: number, ttl: number, throttler: ThrottlerOptions): Promise<boolean> {
136-
const client = context.switchToWs().getClient();
137-
const ip = client._socket.remoteAddress;
138-
const key = this.generateKey(context, ip, throttler.name);
139-
const { totalHits } = await this.storageService.increment(key, ttl);
135+
async handleRequest(requestProps: ThrottlerRequest): Promise<boolean> {
136+
const { context, limit, ttl, throttler, blockDuration, getTracker, generateKey } = requestProps;
140137

141-
if (totalHits > limit) {
142-
throw new ThrottlerException();
138+
const client = context.switchToWs().getClient();
139+
const tracker = client._socket.remoteAddress;
140+
const key = generateKey(context, tracker, throttler.name);
141+
const { totalHits, timeToExpire, isBlocked, timeToBlockExpire } =
142+
await this.storageService.increment(key, ttl, limit, blockDuration, throttler.name);
143+
144+
const getThrottlerSuffix = (name: string) => (name === 'default' ? '' : `-${name}`);
145+
146+
// Throw an error when the user reached their limit.
147+
if (isBlocked) {
148+
await this.throwThrottlingException(context, {
149+
limit,
150+
ttl,
151+
key,
152+
tracker,
153+
totalHits,
154+
timeToExpire,
155+
isBlocked,
156+
timeToBlockExpire,
157+
});
143158
}
144159

145160
return true;

0 commit comments

Comments
 (0)