【问题标题】:How to configure rate-limit with fastify-adapter in nest js如何在 Nest js 中使用 fastify-adapter 配置速率限制
【发布时间】:2019-10-14 11:51:10
【问题描述】:

我刚开始实现 API 的 Nest js,我正在使用 Fastify 适配器。 我需要帮助在 Nest JS 中使用 FastifyAdapter 配置速率限制。

async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
        AppModule,
        new FastifyAdapter(),
    );

    const limiter = fastifyRateLimit(fastify(), {
        timeWindow: 15 * 60 * 1000, // 15 minutes
        max: 100 // limit each IP to 100 requests per windowMs
    }, (err) => {
    });
    app.use(limiter);
    await app.listen(configService.getPort());
}

bootstrap();

请参考以上代码并改正错误

【问题讨论】:

  • 你是怎么得到fastify()的?
  • 我使用 npm 安装
  • 不,在您看到速率限制器的代码中,您有 fastify() 但我没有看到 fastify 在其他任何地方初始化

标签: node.js nestjs rate-limiting fastify nestjs-fastify


【解决方案1】:

安装:

npm install fastify-rate-limit --save

导入(在 main.ts 中):

import * as fastifyRateLimit from 'fastify-rate-limit';

用法:

async function bootstrap() {
  // Create our app, bootstrap using fastify
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter()
  );

  // Apply rate limiter
  app.register(fastifyRateLimit, {
    max: 25,
    timeWindow: '1 minute'
  });
}

【讨论】:

  • 通过在应用程序级别注册它,它将对所有路线都有效,但是如何更改特定路线的限制?我想创建一个装饰器来覆盖某些路由的默认限制。这是正确的做法吗?
  • @NicolasOste 我相信 Fastify 不支持此功能。我已经离开了 Fastify。虽然理论上很好,但事实证明它与某些功能不兼容,并且总体上没有足够的性能提升来让额外的头痛。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 2021-02-09
  • 1970-01-01
相关资源
最近更新 更多