简体   繁体   中英

ThrottlerGuard not working on Websocket in Nestjs

I'm creating an application that is using Nestjs with websockets, but now I need to add rate limit on the sockets, but analyzing the documentation documentation link and implementing what it says in it, when I use @UseGuards(MyGuard) an error occurs in the application.

My Guard:

@Injectable()
export class NewThrottlerGuard extends ThrottlerGuard {
  protected async handleRequest(
    context: ExecutionContext,
    limit: number,
    ttl: number,
  ): Promise<boolean> {
    console.log('Request');
    const client = context.switchToWs().getClient();
    const ip = client.conn.remoteAddress;
    const key = this.generateKey(context, ip);
    const ttls = await this.storageService.getRecord(key);

    if (ttls.length >= limit) {
      throw new ThrottlerException();
    }

    await this.storageService.addRecord(key, ttl);
    return true;
  }
}

Websocket:

@UseGuards(NewThrottlerGuard)
@SubscribeMessage('sendMessage')
sendMessage(
  @ConnectedSocket() client: Socket,
  @MessageBody() message: string,
) {
  client.rooms.forEach((room) => {
    if (room !== client.id) {
      client.broadcast.to(room).emit('message', message);
    }
  });
}

Error in console:

/node_modules/@nestjs/common/utils/validate-each.util.js:22
    throw new InvalidDecoratorItemException(decorator, item, context.name);
          ^
Error: Invalid guard passed to @UseGuards() decorator (ChatGateway).
at validateEach

The file in: @nestjs/common/utils/validate-each.util.js:22

function validateEach(context, arr, predicate, decorator, item) {
    if (!context || !context.name) {
        return true;
    }
    console.log(context, arr)
    const errors = arr.some(str => !predicate(str));
    if (errors) {
        throw new InvalidDecoratorItemException(decorator, item, context.name);
    }
    return true;
}

i put some console.log then in the terminal it show:

[Function: ChatGateway] [ undefined ]

In Github Throttler documentation they say: You cannot bind the guard with APP_GUARD or app.useGlobalGuards() due to how Nest binds global guards. So, im using @UseGuards()

The guard itself was written correctly, but it was put in a location that importing it made a circular reference between files, so when @UseGuards() was used it became @UseGuards(undefined) which caused the cryptic error message. Moving the guard to a dedicated file will fix the error

I follow your github reference settings and it doesn't work,The following is my code, where is my setting wrong, and the request to ws is not intercepted(In the handleRequest method) 在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM