NestJS中文文档
迁移到 Nest / 从 Fastify 迁移
已译 191/191

从 Fastify 迁移

Fastify 应用可以迁移到 Nest 并继续使用 Fastify:你的插件照常工作,路由可以一次迁一条,也可以一次全部迁完。

Nest 通过 FastifyAdapter 运行在 Fastify 之上,所以这不是更换服务器。路由器、插件、JSON schema 和序列化都保持不变,包括路径如何匹配、查询字符串如何解析、请求体最大可以多大。你新增的是它们周边的结构:模块、依赖注入,以及取代逐个路由注册的钩子的守卫和管道。

选择方式

问题 一次一条路由 整体迁移
它如何工作? Nest 运行在你的 Fastify 实例之上,路由逐条迁移过来 由一个全新的 Nest 应用在一次发布中替换 Fastify 应用
部署的是什么? 每迁移一条路由就单独部署 一次性部署全部内容
功能开发会怎样? 照常进行,新端点直接写在 Nest 里 要么暂停,要么写两遍,直到切换完成
如何回退? 恢复一条路由即可 重新部署上一个 Fastify 发布版本
需要哪个 Fastify 版本? Fastify 5,因此需先升级 任意版本,因为不会改动 Fastify 应用
现有的插件怎么办? 继续运行,对 Nest 的路由同样生效 在 Nest 应用上重新注册它们
两种写法会在代码里共存多久? 直到最后一条路由迁完 从不共存

当应用规模较大、有多人同时开发,或者无法等待时,就一次迁移一条路由。当应用小到可以作为一处改动来评审,并且你能用测试把它的行为固定下来时,就整体迁移。整体迁移也适合交给编码代理。

一次一条路由

Fastify 应用保留自己的路由、插件和错误处理器,新端点写在 Nest 里,已有端点则在你下次改动它们时迁过去。两者在同一个端口上应答,因此客户端察觉不到变化,而且每一步都可以单独部署。

前置条件

  • Fastify 5。 Nest 的 FastifyAdapter 会注册需要该版本的插件,若换成 Fastify 4 实例,Nest 一启动就会失败。请先升级应用。
  • TypeScript。 本页的 Nest 代码是 TypeScript。如果 Fastify 应用是用 JavaScript 写的,其文件可以保持原样:TypeScript 的 allowJs 选项会把它们与其余代码一起编译。

在 Fastify 旁边安装 Nest:

$ npm i --save @nestjs/core @nestjs/common @nestjs/platform-fastify reflect-metadata rxjs

让 Nest 跑在 Fastify 应用上

Nest 通常会自己创建一个 Fastify 实例。这里改为把你现有的实例交给它。先让应用停止监听,再让一个函数返回该实例。Nest 会设置实例自身的错误处理器和未找到处理器,因此有两处必须改动:

  • 把 setErrorHandler() 移入一个承载你那些路由的插件。它继续处理这些路由的错误,Fastify 也不会再警告它被覆盖。
  • 删除 setNotFoundHandler()。带着 Not found handler already set 这一提示,Nest 会拒绝启动,未知路由由 Nest 自己应答。
legacy/app.ts
export async function buildLegacyApp() {
  const app = Fastify();
  await app.register(helmet);
  await app.register(auth); // 为实例和请求添加装饰
  app.addHook('onRequest', async (request, reply) => {
    reply.header('x-request-id', request.headers['x-request-id'] ?? 'generated');
  });
  await app.register(async (legacy) => {
    legacy.setErrorHandler(errorHandler);
    await legacy.register(ordersRoutes, { prefix: '/api/orders' });
    await legacy.register(miscRoutes, { prefix: '/api' });
  });
  // await app.listen({ port: 3000 }); <- 从此由 Nest 监听
  return app;
}

然后把它传给 FastifyAdapter,由 Nest 来监听:

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

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

await bootstrap();

现在两者都由同一个 Fastify 实例处理请求:

  • Fastify 路由像以前一样应答,它们的错误会到达它们自己的错误处理器。
  • 注册在根实例上的插件和钩子对 Nest 的路由同样生效,因此上面的 helmet 和 onRequest 钩子也会为它们运行,request.jwtVerify() 在 Nest 守卫里同样可用。
  • 注册在封装插件内部的钩子仍留在该插件内部,一如既往,因此不会为 Nest 的路由运行。
  • Nest 路由中的错误会经过它的异常过滤器,两者都没有的路由,其请求由 Nest 返回 404 响应。

迁移一条路由

在 Nest 里写好该路由,并在同一次改动中把它从 Fastify 删除。Fastify 的路由器不接受重复声明,因此若两者都在代码里,应用会在启动时以 Method 'GET' already declared for route 终止。你已有的插件可以支撑一个守卫,@RouteSchema() 则可以直接采用该路由已有的 JSON schema:

authenticated.guard.ts
@Injectable()
export class AuthenticatedGuard implements CanActivate {
  constructor(private readonly users: UsersRepository) {}

  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    try {
      const { sub } = await request.jwtVerify();
      request.user = await this.users.find(sub);
      return true;
    } catch {
      throw new UnauthorizedException();
    }
  }
}
me.controller.ts
@Controller('api')
export class MeController {
  @Get('me')
  @UseGuards(AuthenticatedGuard)
  @RouteSchema({
    response: {
      200: {
        type: 'object',
        properties: { id: { type: 'string' }, email: { type: 'string' } },
      },
    },
  })
  me(@Req() request: { user: User }) {
    return request.user;
  }
}

迁移过程中请随时参阅保持那些会静默变化的行为。它适用于每一条迁走的路由,上面之所以给出响应 schema,正是因为这个原因。

完成迁移

当 Fastify 的路由都消失后,用 app.register() 在 Nest 应用上注册插件,把错误处理器改写为异常过滤器,删除 legacy 文件夹,并用 new FastifyAdapter() 创建应用。

整体迁移

由一个全新的 Nest 应用在一次发布中替换 Fastify 应用。在此之前,Fastify 应用保持原样,它就是新应用必须达到的行为基准。迁移期间请继续使用 FastifyAdapter,即使你打算之后更换适配器:这样路由器、查询解析、请求体大小限制和路径语法都保持不变,一次需要改变的东西就更少。

用测试固定 API 行为

编写只认 URL 的测试,让同一套测试可以分别在两个应用上运行。逐一检查每个插件和每条路由,覆盖每条路由的状态码、响应体和重要响应头,成功与失败的情况都要覆盖。还要检查响应 schema 会剔除哪些字段,确保它们仍然被剔除:

import assert from 'node:assert/strict';
import { test } from 'node:test';

const BASE = process.env.BASE_URL ?? 'http://localhost:3000';

test('the response schema hides internal fields', async () => {
  const res = await fetch(`${BASE}/api/me`, {
    headers: { authorization: `Bearer ${token}` },
  });
  assert.deepEqual(await res.json(), { id: 'u2', email: 'bob@example.com' });
});

test('authentication comes before validation', async () => {
  const res = await fetch(`${BASE}/api/orders`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ total: -1 }),
  });
  assert.equal(res.status, 401);
});

在编写任何 Nest 代码之前,先让这些测试在 Fastify 应用上全部通过:

$ BASE_URL=http://localhost:3000 node --test test/contract.test.mjs

翻译应用

用 nest new 在 Fastify 应用旁边创建 Nest 应用,把它切换为 FastifyAdapter,并把每个路由插件迁移为一个控制器:

Fastify Nest
app.register(routes, {{ '{' }} prefix {{ '}' }}) 模块中的控制器,即 @Controller('api/orders')
app.get('/:id', handler) 方法上的 @Get(':id')
request.params、request.query、request.body @Param()、@Query()、@Body()
schema: {{ '{' }} querystring, body, response {{ '}' }} @nestjs/platform-fastify 的 @RouteSchema(),传入相同的 JSON schema
onRequest: app.authenticate 一个守卫
preHandler: app.requireRole('admin') 路由上的元数据,由守卫读取
诸如 request.jwtVerify() 这样的装饰 在 @Req() 上做同样的调用,并注册相应插件
reply.code(201).send(x) return x;状态码不是默认值时再加 @HttpCode()
reply.code(204).send() @HttpCode(204),并且不返回任何内容
reply.redirect(url, 301) @Redirect(url, 301)
reply.setCookie() @Res({{ '{' }} passthrough: true {{ '}' }}) reply,然后照常调用 reply.setCookie() 并 return
reply.type('application/json') @Header('content-type', 'application/json')
reply.send(stream) new StreamableFile(stream, {{ '{' }} type {{ '}' }})
await request.file() 在 @Req() 上做同样的调用,并注册 @fastify/multipart
app.register(plugin, options) app.register(plugin, options)
app.addHook('onRequest', fn) app.getHttpAdapter().getInstance().addHook('onRequest', fn)
setErrorHandler() 与 setNotFoundHandler() 一个全局异常过滤器
为实例装饰数据库连接池的插件 一个提供者

路由路径保持原样,因为读取它们的是同一个路由器:search/:term?、items/:id(^\\d+$) 和 assets/*,后者用 @Param('*') 取参数。

保持那些会静默变化的行为

其中有两项会在完全不报错的情况下泄露数据,所以先检查它们:

在 Fastify 中 在 Nest 应用中 要保留旧行为
响应 schema 会剔除它未列出的每一个字段,因此处理器可以返回整条记录 没有 schema 时每个字段都会被发送,包括 passwordHash 在原先有 schema 的每条路由上加 @RouteSchema({{ '{' }} response {{ '}' }})
POST 应答 200,且 response: {{ '{' }} 200: schema {{ '}' }} 会生效 POST 应答 201,因此以 200 为键的 schema 不再生效,那些字段也会一并返回 @HttpCode(200),或把 schema 改为以 201 为键
onRequest 中的认证先于校验运行,因此没有 token 的非法请求得到 401 @RouteSchema({{ '{' }} body {{ '}' }}) 在任何守卫之前完成校验,因此该请求得到校验错误 在需要如此的路由上改用管道校验,即 @Body({{ '{' }} schema {{ '}' }}),它在守卫之后运行
错误具有你的处理器赋予它的结构 {{ '{' }} statusCode, message, error {{ '}' }} 一个全局异常过滤器
校验错误带着 err.validation 到达你的处理器 它以同样的方式到达过滤器,即 exception.validation 同一个过滤器
未知路由进入你的未找到处理器 NotFoundException,响应体是 Nest 的 同一个过滤器

过滤器必须让每一个错误都保持你的错误结构,包括 Nest 和 Fastify 自己抛出的错误。格式错误的 JSON、超出大小限制的请求体这类请求体错误,会以 HttpException 的形式到达:

common/api-exception.filter.ts
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const http = host.switchToHttp();
    const request = http.getRequest<FastifyRequest>();
    const reply = http.getResponse<FastifyReply>();
    const send = (status: number, code: string, message: string) =>
      reply.code(status).send({ error: { code, message } });

    if (exception instanceof ApiError) {
      return send(exception.status, exception.code, exception.message);
    }
    if (exception instanceof NotFoundException) {
      return send(404, 'NOT_FOUND', `No route for ${request.method} ${request.url}`);
    }
    if (exception?.validation) {
      return send(422, 'INVALID_INPUT', exception.message);
    }
    const status =
      exception instanceof HttpException ? exception.getStatus() : exception?.statusCode;
    if (status === 400) {
      return send(400, 'BAD_REQUEST', 'Malformed request');
    }
    if (status && status < 500) {
      return send(status, exception.code ?? 'ERROR', exception.message);
    }
    return send(500, 'INTERNAL', 'Something went wrong');
  }
}
main.ts
async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  await app.register(helmet);
  await app.register(cors, { origin: 'https://shop.example.com', credentials: true });
  await app.register(cookie);
  await app.register(multipart, { limits: { fileSize: 1024 * 1024 } });
  await app.register(fastifyStatic, {
    root: join(import.meta.dirname, '..', 'public'),
    prefix: '/static/',
  });
  await app.register(jwt, { secret: process.env.JWT_SECRET });
  app.getHttpAdapter().getInstance().addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {
    reply.header('x-request-id', request.headers['x-request-id'] ?? 'generated');
  });
  app.useGlobalFilters(new ApiExceptionFilter());
  await app.listen(process.env.PORT ?? 3000);
}

await bootstrap();

切换上线

对 Nest 应用运行同一套测试,并修复应用,而不是改测试:

$ BASE_URL=http://localhost:3001 node --test test/contract.test.mjs

测试全部通过后,用它替换 Fastify 应用部署上线,并保持上一个 Fastify 发布版本仍可部署,直到新版本已经承载真实流量。

交给编码代理

两种方式都可以配合编码代理,而当应用小到可以作为一处改动来评审时,整体迁移更合适。让代理阅读本页,并以测试为准绳,这样它就无法仅凭代码能编译就宣称成功:

Migrate this Fastify application to NestJS all at once, on the FastifyAdapter,
following https://docs.nestjs.com/migrating/fastify.md.

1. Before changing anything, write black-box HTTP tests that cover every
   route: status codes, bodies and important headers, failures included.
   Assert that fields a response schema removes stay removed.
   Run them against the Fastify app until they all pass.
2. Build the Nest application next to it, using the page's translation table.
3. Check every row of "Keep what would change without an error".
4. Run the same tests against the Nest application. Don't edit a test to
   make it pass. If behavior has to change, stop and tell me.