Skip to content

Commit a8b2631

Browse files
committed
docs(throttler): updates throttler docs with re-write
1 parent 3c9748d commit a8b2631

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

content/security/rate-limiting.md

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,43 @@ There is also the `@Throttle()` decorator which can be used to override the `lim
3939

4040
#### Websockets
4141

42-
This module does work with websockets as well, with some limited functionality. First of all, user agent headers are not taken into consideration due to the difference in the underlying transport layer of Socket.IO vs Websockets. The other thing to make note of is that globally bound guards do not activate on websocket gateways, so you **must** bind the guard to the gateway itself using `@UseGuards()`.
42+
This module _can_ work with websockets, but it requires some class extension. You can extend the `ThrottlerGuard` and override the `handleRequest` method like so:
43+
44+
```typescript
45+
@Injectable()
46+
export class WsThrottlerGuard extends ThrottlerGuard {
47+
async handleRequest(context: ExecutionContext, limit: number, ttl: number): Promise<boolean> {
48+
const client = context.switchToWs().getClient();
49+
const ip = client.conn.remoteAddress;
50+
const key = this.generateKey(context, ip);
51+
const ttls = await this.storageService.getRecord(key);
52+
53+
if (ttls.length >= limit) {
54+
throw new ThrottlerException();
55+
}
56+
57+
await this.storageService.addRecord(key, ttl);
58+
return true;
59+
}
60+
}
61+
```
62+
63+
> info **Hint** If you are using the `@nestjs/platform-ws` package you can use `client._socket.remoteAddress` instead.
4364
4465
#### GraphQL
4566

46-
Currently, only GraphQL with Express is supported, but Fastify support is coming as well. This module makes use of setting headers through the `res` object and reading headers through the `req` object of Express. To make sure these are available, when configuring your GraphQLModule, make sure the option `context: ({{ '{' }} req, res {{ '}' }}) => ({{ '{' }} req, res {{ '}' }})` is set.
67+
The `ThrottlerGuard` can also be used to work with GraphQL requests. Again, the guard can be extended, but this tme the `getRequestResponse` method will be overridden
68+
69+
```typescript
70+
@Injectable()
71+
export class GqlThrottlerGuard extends ThrottlerGuard {
72+
getRequestResponse(context: ExecutionContext): { req: Record<string, any>, res: Record<string, any> } {
73+
const gqlCtx = GqlExecutionContext.create(context);
74+
const ctx = gql.getContext();
75+
return { req, ctx.req, res: ctx.res }
76+
}
77+
}
78+
```
4779

4880
#### Configuration
4981

0 commit comments

Comments
 (0)