插件编写与注册
Fastify 插件机制允许你将功能模块化,实现代码复用、作用域隔离与配置注入。插件可以封装路由、装饰器、中间件、钩子等逻辑。
编写基本插件
Fastify 插件本质是一个函数,接收两个参数:fastify 实例与 options 配置对象。
// hello-plugin.js
async function helloPlugin(fastify, options) {
fastify.get('/hello', async () => {
return { msg: `Hello ${options.name}` };
});
}
module.exports = helloPlugin;
注册插件
在主程序中使用 register() 方法注册插件,并传入配置项:
const fastify = require('fastify')();
fastify.register(require('./hello-plugin'), { name: 'Fastify' });
fastify.listen({ port: 3000 });
访问 /hello 会返回:
{ "msg": "Hello Fastify" }
使用 fastify-plugin 显式声明插件
为确保插件可以被其他插件访问,推荐使用 fastify-plugin:
npm install fastify-plugin
// hello-plugin.js
const fp = require('fastify-plugin');
async function helloPlugin(fastify, options) {
fastify.decorate('sayHi', () => `Hi, ${options.name}`);
}
module.exports = fp(helloPlugin);
注册后即可在其他地方访问 fastify.sayHi()。
同步插件
虽然推荐使用 async 函数,Fastify 也支持同步插件写法:
function syncPlugin(fastify, options, done) {
fastify.decorate('x', 123);
done();
}
module.exports = syncPlugin;
注册时使用 .register(syncPlugin) 即可。
插件内部注册子插件
插件可以嵌套注册其他插件,实现模块组合:
async function parentPlugin(fastify) {
fastify.register(async function child(fastify) {
fastify.get('/child', async () => 'from child');
});
}
module.exports = parentPlugin;
设置作用域与隔离
默认插件是作用域隔离的,除非使用 fastify-plugin 显式暴露。
示例:
// a-plugin.js
fastify.decorate('aaa', '123'); // 默认只在当前插件中可见
其他插件访问不到 aaa,除非通过 fastify-plugin 注册为全局插件。
插件文件结构建议
为保持项目整洁,可将插件放置于独立目录:
src/
├── plugins/
│ ├── db.js
│ └── auth.js
注册:
fastify.register(require('./plugins/db'));
fastify.register(require('./plugins/auth'));
每个插件都应专注于单一职责,便于管理与测试。
相关内容
- Fastify 与 Express 对比 本节将对 Fastify 和 Express 两个流行的 Node.js 框架进行对比,帮助开发者理解它们的异同以及在不同场景下的选择。
- 中间件迁移指南 本节介绍如何在 Fastify 中迁移中间件,帮助开发者从其他框架(如 Express)迁移到 Fastify,理解 Fastify 中间件的工作方式,并学习如...
- 常用插件清单 本节列出了一些常用的 Fastify 插件,帮助开发者更好地扩展和定制 Fastify 应用。
- 核心 API 介绍 介绍 Fastify 中常用的核心 API,包括路由注册、请求与响应对象、日志等。
- Hello World 快速上手 Fastify,编写第一个 “Hello World” 应用,体验其简洁的 API 和高性能启动。
- 请求与响应对象 详解 Fastify 中的 request 和 reply 对象,用于获取请求信息和构造响应。