如何将提供路由的Fastify TypeScript插件拆分为多个文件?
解决Fastify TypeScript插件路由拆分后访问实例及装饰对象的问题
方案1:通过闭包直接访问Fastify实例(推荐,类型友好)
把每个路由组封装成接收Fastify实例的函数,处理器在函数内部定义,直接通过闭包访问实例及其装饰对象。
拆分后的路由文件(如example1.route.ts):
import { FastifyInstance } from "fastify"; export default function registerExample1Routes(fastify: FastifyInstance) { // 处理器直接闭包访问fastify async function exampleHandler(request, reply) { console.log(fastify.promptExecutor); return "Example1"; } fastify.get("/example1", exampleHandler); }
主插件文件:
import { FastifyPluginAsync } from "fastify"; import registerExample1Routes from "./example1.route"; import registerExample2Routes from "./example2.route"; const example: FastifyPluginAsync = async (fastify, opts): Promise<void> => { // 注册各路由组 registerExample1Routes(fastify); registerExample2Routes(fastify); }; export default example;
这种这种方式无需额外传递参数,TypeScript能自动推断fastify的类型(包括你装饰的promptExecutor),代码简洁且类型安全。
方案2:通过request.server访问Fastify实例
Fastify的request对象内置server属性,指向当前Fastify实例,处理器可直接通过它访问装饰对象,适合把处理器和路由注册完全分离的场景。
处理器文件(如example1.handler.ts):
export async function exampleHandler(request, reply) { // 通过request.server获取实例 console.log(request.server.promptExecutor); return "Example1"; }
路由注册文件(如example1.route.ts):
import { FastifyInstance } from "fastify"; import { exampleHandler } from "./example1.handler"; export default function registerExample1Routes(fastify: FastifyInstance) { fastify.get("/example1", exampleHandler); }
主插件文件同方案1
这个方案让处理器更独立,不依赖路由注册时的上下文,适合复杂项目中职责分离的场景。
为什么你之前的bind方式会失败?
Async函数作为Fastify路由处理器时,bind绑定的this会被Fastify的调用上下文覆盖(或在严格模式下直接变为undefined),Fastify并不保证路由处理器的this指向实例,因此不推荐用this访问实例。
内容的提问来源于stack exchange,提问作者fozziethebeat
相关产品推荐
相关产品推荐

