Nest 切换 Express 和 Fastify
注意
NestJS 默认使用 Express 作为底层 HTTP 服务器,但也可以切换到 Fastify。
在切换之前,需要先安装 Fastify 和 Fastify 的 NestJS 插件。
express
是 NestJs 默认的 http 库
他遵循的是洋葱模型如下图
Nest 切换
切换 Fasitify
安装
ts
pnpm install fastify @nestjs/platform-fastify
修改 app.module.ts
ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import {
FastifyAdapter,
NestFastifyApplication,
} from "@nestjs/platform-fastify";
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
await app.listen(process.env.PORT ?? 5000);
}
bootstrap();
修改各自对应的控制器
我这里拿 app.controller.ts 举例
代码如下:
ts
import { Controller, Get, Request, Response } from "@nestjs/common";
import { FastifyReply, FastifyRequest } from "fastify";
import { AppService } from "./app.service";
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(
@Request() request: FastifyRequest,
@Response() reply: FastifyReply
) {
reply.header("url", request.url);
reply.send("hello");
}
@Get("/test")
getHello2(
@Request() request: FastifyRequest,
@Response({ passthrough: true }) reply: FastifyReply
) {
reply.header("url", request.url);
// reply.send('hello');
return "hello23232";
}
}
- 两种返回方法
注意
两种都是通过@Response 来返回
第一种通过 FastifyReply 里面的 send 方法来返回
第二种通过 return 来返回具体的数据