@@ -102,26 +102,30 @@ This module can work with websockets, but it requires some class extension. You
102102``` typescript
103103@Injectable ()
104104export 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 > {
110106 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 ;
112112 const key = this .generateKey (context , ip );
113- const ttls = await this .storageService .getRecord (key );
113+ const { totalHits } = await this .storageService .increment (key , ttl );
114114
115- if (ttls . length >= limit ) {
115+ if (totalHits > limit ) {
116116 throw new ThrottlerException ();
117117 }
118118
119- await this .storageService .addRecord (key , ttl );
120119 return true ;
121120 }
122121}
123122```
124123
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+
125129> info ** Hint** If you are using the ` @nestjs/platform-ws ` package you can use ` client._socket.remoteAddress ` instead.
126130
127131#### GraphQL
0 commit comments