关于 fastify-best-practise
供 Agent 构建或审查 Fastify 应用的规则型技能,按主题整理指导,并提供错误与正确示例、影响评级和文档参考。
主要功能
- 01按主题组织 Fastify 规则
- 02提供错误与正确示例
- 03标注规则影响评级
- 04涵盖生产环境相关事项
- 05按任务选择规则
适用场景
- 01搭建新的 Fastify 项目
- 02审查路由和 Schema 模式
- 03规划身份验证与错误处理
- 04准备测试和部署
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ thecodepace/ fastify-skills --skill fastify-best-practise安装后在 Claude Code 中输入/fastify-best-practise确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
rules/_template.mdauthentication.mdautoload.mdclean-architecture.mdconfiguration.mdcontent-type-parser.mdcors-security.mdcreate-plugin.mdcreate-server.mddatabase-integration.mddatabase-migrations.mddecorators.mddelay-accepting-requests.mddeployment.mdencapsulation.mderror-handling.mdhooks-lifecycle.mdhttp-proxy.mdhttp-query.mdhttp2.mdlogging.mdmultipart.mdperformance.mdrate-limiting.mdroute-best-practices.mdschema-validation-zod.mdserialization-zod.mdserialization.mdtest-containers.mdtesting.md详细介绍
Fastify 最佳实践
精选的一组规则和模式,用于构建可用于生产环境的 Fastify 应用。每条规则都包含错误和正确示例及其说明。
工作原理
- Agent 识别出用户正在使用 Fastify 或询问 Fastify 模式
- 根据主题(路由、验证、封装等)加载相关规则文件
- Agent 在生成或审查代码时应用规则中的最佳实践
规则
规则按主题整理在 rules/ 目录中。每条规则都遵循统一格式,包含影响评级、错误和正确示例,以及官方文档的参考链接。
| 规则 | 文件 | 影响 | 描述 |
|---|---|---|---|
| 配置 | configuration.md | HIGH | 环境配置、日志记录器设置、安全选项和优雅关闭 |
| 创建服务端 | create-server.md | LOW-MEDIUM | 使用 buildServer() 工厂函数,创建可复用、可测试的服务端 |
| 创建插件 | create-plugin.md | LOW-MEDIUM | 使用 fastify-plugin 将可复用功能封装到插件中 |
| 自动加载 | autoload.md | HIGH | 使用 @fastify/autoload 从文件系统自动加载插件和路由 |
| 路由最佳实践 | route-best-practices.md | MEDIUM | 使用插件/前缀组织路由、采用异步处理程序,并完整配置路由选项 |
| Schema 验证(Zod) | schema-validation-zod.md | HIGH | 使用 Zod + fastify-type-provider-zod 进行类型安全验证 |
| 序列化(Zod) | serialization-zod.md | HIGH | 使用 Zod schemas 进行类型安全的响应序列化、输出验证,并提供兼容性说明 |
| 封装 | encapsulation.md | HIGH | 正确隔离作用域,并了解何时使用 fastify-plugin |
| 错误处理 | error-handling.md | HIGH | 自定义错误处理程序、@fastify/error、404 处理和结构化响应 |
| 钩子与生命周期 | hooks-lifecycle.md | MEDIUM | 所有请求/响应和应用程序钩子:onRequest、preParsing、preValidation、preHandler、preSerialization、onError、onSend、onResponse、onReady、onClose |
| 日志记录 | logging.md | HIGH | 内置 Pino 日志记录器、请求关联、敏感信息脱敏和子日志记录器 |
| 身份验证 | authentication.md | HIGH | 使用 @fastify/jwt 进行 JWT 身份验证,使用 @fastify/auth 实现多策略身份验证 |
| 测试 | testing.md | HIGH | 使用 inject()、buildServer 模式、vitest/node:test 进行测试 |
| TypeScript | typescript-integration.md | MEDIUM | 类型提供器、模块扩充、带类型的装饰器 |
| 装饰器 | decorators.md | MEDIUM | 使用 decorate / decorateRequest / decorateReply 扩展 Fastify 实例、请求和响应 |
| 内容类型解析器 | content-type-parser.md | HIGH | 自定义内容类型解析器、请求体限制、多部分上传、全匹配和正则匹配 |
| 多部分数据与文件上传 | multipart.md | HIGH | 使用 @fastify/multipart 上传文件、流式处理、大小限制和 MIME 验证 |
| WebSocket | websockets.md | HIGH | 使用 @fastify/websocket 实现实时双向连接,处理生命周期、广播和身份验证 |
| HTTP 代理 | http-proxy.md | HIGH | 使用 @fastify/http-proxy 和 @fastify/reply-from 实现 API 网关/BFF 模式、身份验证钩子、错误处理和多上游路由 |
| HTTP QUERY 方法 | http-query.md | HIGH | 在 Fastify 5.11+ 中使用原生 RFC 10008 QUERY 路由;验证请求体和媒体类型,采用安全/幂等的处理程序,并遵守缓存和 CORS 约束 |
| 类型提供器 | type-providers.md | HIGH | 比较 TypeBox、json-schema-to-ts 和 Zod 提供器;.withTypeProvider<T>();插件中的作用域提供器;特定提供器的插件类型 |
| 部署 | deployment.md | HIGH | 使用 close-with-grace 优雅关闭、存活/就绪探针、监听 0.0.0.0、trustProxy、多阶段 Dockerfile 和 AWS Lambda 适配器 |
| HTTP/2 | http2.md | MEDIUM | 启用基于 TLS 的 HTTP/2(h2)并回退到 HTTP/1.1,或为内部服务使用明文 h2c;带类型的 buildServer 工厂 |
| CORS 与安全标头 | cors-security.md | HIGH | 使用 @fastify/cors 配置允许列表(静态和动态),使用 @fastify/helmet 配置 CSP/HSTS、注册顺序和组合式安全插件 |
| 延迟接受请求 | delay-accepting-requests.md | HIGH | 依赖项就绪前以 503 拒绝请求;了解 Kubernetes 的存活探针与就绪探针之别 |
| 数据库集成 | database-integration.md | HIGH | 将 pg 连接池注册为 Fastify 插件;使用 @nearform/sql 执行安全查询 |
| 数据库迁移 | database-migrations.md | HIGH | 在启动时运行 Postgrator SQL 迁移;绝不修改已应用的文件 |
| 测试容器 | test-containers.md | HIGH | 使用 Testcontainers 启动真实的 Postgres 容器,以进行集成测试 |
| 整洁架构 | clean-architecture.md | HIGH | 纯服务层函数 + 精简的路由处理程序;显式依赖注入 |
| 单元测试 | unit-testing.md | HIGH | 使用模拟数据库存根,隔离测试服务函数 |
| 性能 | performance.md | HIGH | Schema 预编译、序列化、负载削减、流式处理和基准测试 |
| 速率限制 | rate-limiting.md | HIGH | 使用 @fastify/rate-limit 保护 API,支持单路由覆盖、Redis 存储和自定义键 |
| 序列化 | serialization.md | HIGH | 使用 JSON Schema 和 fast-json-stringify 进行响应序列化 |
用法
生成 Fastify 代码时,请阅读与主题相关的规则文件,并应用其中展示的模式。对于新项目,所有规则都适用。对于特定任务,只加载所需内容:
- 新项目设置:
create-server.md、configuration.md、autoload.md、encapsulation.md、typescript-integration.md - 添加路由:
route-best-practices.md、autoload.md、schema-validation-zod.md、serialization-zod.md、serialization.md - 添加共享服务:
create-plugin.md、autoload.md、encapsulation.md - 配置/环境:
configuration.md - 错误处理:
error-handling.md - 身份验证/中间件:
authentication.md、hooks-lifecycle.md、encapsulation.md - 速率限制:
rate-limiting.md、hooks-lifecycle.md - 自定义装饰器:
decorators.md、typescript-integration.md - 日志记录:
logging.md - 请求体解析/文件上传:
content-type-parser.md、multipart.md - 架构 / 类型提供程序:
schema-validation-zod.md、serialization-zod.md、serialization.md、type-providers.md - HTTP/2 / TLS:
http2.md、configuration.md - CORS / 安全标头:
cors-security.md、rate-limiting.md - 生产环境部署:
deployment.md、delay-accepting-requests.md、configuration.md - 实时通信 / WebSockets:
websockets.md、authentication.md、hooks-lifecycle.md - API 网关 / 代理:
http-proxy.md、hooks-lifecycle.md、error-handling.md - 启动 / 健康检查:
delay-accepting-requests.md、hooks-lifecycle.md、configuration.md - 性能调优:
performance.md、schema-validation-zod.md - 编写测试:
testing.md、create-server.md - 数据库设置:
database-integration.md、database-migrations.md - 使用真实数据库进行集成测试:
test-containers.md、testing.md - 清晰划分关注点:
clean-architecture.md、unit-testing.md - 业务逻辑单元测试:
unit-testing.md、clean-architecture.md - 包含请求体的安全查询(QUERY 方法):
http-query.md、schema-validation-zod.md、cors-security.md - 响应序列化:
serialization.md、serialization-zod.md、schema-validation-zod.md
推荐的项目结构
使用 @fastify/autoload,插件和路由会从各自目录中自动加载:
src/
plugins/ # Autoloaded — shared plugins (use fastify-plugin)
db.ts # Database client (pg/Drizzle/Prisma) + lifecycle
auth.ts
config.ts
routes/ # Autoloaded — encapsulated route plugins (NO fastify-plugin)
_hooks.ts # Global route hooks (with autoHooks: true)
users/
index.ts # → /users (thin handler — calls services/users.ts)
_hooks.ts # Hooks for /users scope only
schema.ts # Zod schemas
posts/
index.ts # → /posts
schema.ts
services/ # Pure business logic — no Fastify imports, injectable deps
users.ts
posts.ts
db/
migrate.ts # runMigrations() helper (uses Postgrator)
server.ts # buildServer() with autoload registration
app.ts # Entry point — runMigrations() then server.listen()
migrations/ # Raw SQL files (committed to git): 001.do.*.sql, 001.undo.*.sql
test/
services/
users.test.ts # Unit tests — pure functions, mock db
routes/
users.test.ts # Integration tests — inject() + real schema
helpers/
server.ts # createTestServer() / createIntegrationServer()
db.ts # startTestDatabase() via Testcontainers
向用户呈现结果
应用这些最佳实践时,请说明遵循了哪些规则:
已应用 Fastify 最佳实践:
- 路由组织:按资源分组路由,并使用前缀
- Zod 验证与序列化:为请求和响应定义架构,支持类型推断和输出验证
- 封装:共享插件使用
fastify-plugin,路由保持作用域隔离- 错误处理:使用
@fastify/error定义自定义错误处理器- 性能:响应架构、共享架构引用、负载削减、流式处理和基准测试指南
- 数据库:将客户端注册为使用
fastify-plugin的插件,以便共享连接池并管理生命周期- 迁移:在服务器启动前通过 Postgrator(
runMigrations())应用迁移;原始 SQL 文件由 git 跟踪- 整洁架构:业务逻辑放在纯服务函数中;路由处理器保持精简
- 单元测试:使用模拟数据库存根,对服务函数进行隔离测试
- HTTP QUERY 方法:原生 Fastify 5.11+ RFC 10008 路由——请求体和媒体类型验证、安全/幂等的处理器、考虑请求体的缓存键、可选的发现/资源标头,以及 CORS 预检支持
- 集成测试:通过 Testcontainers 使用真实的 Postgres 容器
参考
评论
支持 Markdown