@@ -102,26 +102,30 @@ This module can work with websockets, but it requires some class extension. You
102
102
``` typescript
103
103
@Injectable ()
104
104
export class WsThrottlerGuard extends ThrottlerGuard {
105
- async handleRequest(
106
- context : ExecutionContext ,
107
- limit : number ,
108
- ttl : number ,
109
- ): Promise <boolean > {
105
+ async handleRequest(context : ExecutionContext , limit : number , ttl : number ): Promise <boolean > {
110
106
const client = context .switchToWs ().getClient ();
111
- const ip = client .conn .remoteAddress ;
107
+ // this is a generic method to switch between `ws` and `socket.io`. You can choose what is appropriate for you
108
+ const ip = [' conn' , ' _socket' ]
109
+ .map ((key ) => client [key ])
110
+ .filter ((obj ) => obj )
111
+ .shift ().remoteAddress ;
112
112
const key = this .generateKey (context , ip );
113
- const ttls = await this .storageService .getRecord (key );
113
+ const { totalHits } = await this .storageService .increment (key , ttl );
114
114
115
- if (ttls . length >= limit ) {
115
+ if (totalHits > limit ) {
116
116
throw new ThrottlerException ();
117
117
}
118
118
119
- await this .storageService .addRecord (key , ttl );
120
119
return true ;
121
120
}
122
121
}
123
122
```
124
123
124
+ There are some things to take keep in mind when working with websockets:
125
+
126
+ - You cannot bind the guard with ` APP_GUARD ` or ` app.useGlobalGuards() ` due to how Nest binds global guards.
127
+ - When a limit is reached, Nest will emit an ` exception ` event, so make sure there is a listener ready for this.
128
+
125
129
> info ** Hint** If you are using the ` @nestjs/platform-ws ` package you can use ` client._socket.remoteAddress ` instead.
126
130
127
131
#### GraphQL
0 commit comments