Skip to content

性能(Fastify)

默认情况下,Nest 使用 Express 框架。如前所述,Nest 还提供了与其他库的兼容性,例如 Fastify。Nest 通过实现框架适配器来实现这种框架独立性,适配器的主要功能是将中间件和处理程序代理到相应的库特定实现。

提示

请注意,要实现框架适配器,目标库必须提供与 Express 中类似的请求/响应管道处理。

Fastify 为 Nest 提供了一个很好的替代框架,因为它以与 Express 类似的方式解决了设计问题。然而,Fastify 比 Express 得多,达到了几乎两倍的基准测试结果。一个合理的问题是,为什么 Nest 使用 Express 作为默认的 HTTP 提供者?原因是 Express 被广泛使用、众所周知,并且拥有大量的兼容中间件,这些中间件对 Nest 用户来说是开箱即用的。

但由于 Nest 提供了框架独立性,你可以轻松地在它们之间迁移。当你非常看重高性能时,Fastify 可能是更好的选择。要使用 Fastify,只需选择本章所示的内置 FastifyAdapter 即可。

安装

首先,我们需要安装所需的包:

bash
$ npm i --save @nestjs/platform-fastify

适配器

安装 Fastify 平台后,我们可以使用 FastifyAdapter

typescript
// main.ts
import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter()
  );
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

默认情况下,Fastify 仅监听 localhost 127.0.0.1 接口(了解更多)。如果你想接受来自其他主机的连接,你应该在 listen() 调用中指定 '0.0.0.0'

typescript
async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  await app.listen(3000, '0.0.0.0');
}

平台特定包

请记住,当你使用 FastifyAdapter 时,Nest 使用 Fastify 作为 HTTP 提供者。这意味着依赖于 Express 的每个配方可能不再工作。你应该改用 Fastify 等效包。

重定向响应

Fastify 处理重定向响应的方式与 Express 略有不同。要使用 Fastify 进行正确的重定向,请返回状态码和 URL,如下所示:

typescript
@Get()
index(@Res() res) {
  res.status(302).redirect('/login');
}

Fastify 选项

你可以通过 FastifyAdapter 构造函数将选项传递给 Fastify 构造函数。例如:

typescript
new FastifyAdapter({ logger: true });

中间件

中间件函数获取原始的 reqres 对象,而不是 Fastify 的包装器。这是 middie 包(在底层使用)和 fastify 的工作方式——查看此页面了解更多信息。

typescript
// logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { FastifyRequest, FastifyReply } from 'fastify';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void) {
    console.log('Request...');
    next();
  }
}

路由配置

你可以使用 @RouteConfig() 装饰器来使用 Fastify 的路由配置功能。

typescript
@RouteConfig({ output: 'hello world' })
@Get()
index(@Req() req) {
  return req.routeConfig.output;
}

路由约束

从 v10.3.0 开始,@nestjs/platform-fastify 支持 Fastify 的路由约束功能,使用 @RouteConstraints 装饰器。

typescript
@RouteConstraints({ version: '1.2.x' })
newFeature() {
  return 'This works only for version >= 1.2.x';
}

提示

@RouteConfig()@RouteConstraints@nestjs/platform-fastify 导入。

示例

一个可用的示例在这里

基于 NestJS 官方文档翻译