Skip to content

如何切换到 Fastify

Express

之前我们用的 Response、Request 对象都是 Express 的,并且 Nest 也支持 Express 的中间件机制。

Express 是一个处理后端请求的库。下面的这段代码是 Express 作为 HTTP 服务器的简单示例。

js
// Import the Express library.
const express = require('express');

// Initializing the app.
const app = express();

// Getting the path request and sending the response with text
app.get('/', (req,res) => {
    res.send('Hi, your request has been received');
});

// Listen on port 2000
app.listen(2000, () => {
    console.log('listening at http://localhost:2000');
});

默认情况下,Nest 使用 Express 作为底层框架。Nest 也提供了切换成其他框架(如 Fastify)的能力。Nest 通过实现接口来调用不同的框架。

切换到 Fastify

想要切换到 Fastify,首先要安装对应的依赖。

sh
pnpm add fastify @nestjs/platform-fastify

在 Nest 的入口处引入 Fasitfy。

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(3000);
}

bootstrap();

在 Controller 处,我们可以通过 Fastify 来处理 Request 和 Response 了。

ts
import { Controller, Get, Request, Response } from '@nestjs/common';
import { AppService } from './app.service';
import { FastifyReply, FastifyRequest } from 'fastify';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(
    @Request() request: FastifyRequest,
    @Response() reply: FastifyReply,
  ): void {
    reply.header('url', request.url);
    reply.send('Hello World!');
  }
}

Released under the MIT License.