SuperAPI AI 工具集

fastify-best-practices

编程与开发

查看项目

更新于 10-15 10:24

技能介绍

用途

fastify-best-practices 用于指导 Fastify Node.js 后端服务器和 REST API 的开发,支持 TypeScript 或 JavaScript。当你需要开发基于 Fastify 的后端应用、实现 Fastify 插件和路由处理器、获取 Fastify 架构与模式方面的指引、在 Fastify 中使用 TypeScript、使用 Fastify 的 inject 方法进行测试,或配置校验、序列化与错误处理时,可以使用该技能。

主要能力

该技能以规则文件的形式组织内容,按主题提供详细说明和代码示例:

  • plugins.md — 插件开发与封装
  • routes.md — 路由组织与处理器
  • schemas.md — JSON Schema 校验
  • error-handling.md — 错误处理模式
  • hooks.md — 钩子与请求生命周期
  • authentication.md — 认证与授权
  • testing.md — 使用 inject() 进行测试
  • performance.md — 性能优化
  • logging.md — 使用 Pino 进行日志记录
  • typescript.md — TypeScript 集成
  • decorators.md — 装饰器与扩展
  • content-type.md — 内容类型解析
  • serialization.md — 响应序列化
  • cors-security.md — CORS 与安全头
  • websockets.md — WebSocket 支持
  • database.md — 数据库集成模式
  • configuration.md — 应用配置
  • deployment.md — 生产部署
  • http-proxy.md — HTTP 代理与 reply.from()

使用方式

按照主题阅读各个规则文件,获取详细说明和代码示例。资料给出了针对常见场景的推荐阅读顺序:

  • 刚接触 Fastify:从 plugins.md → routes.md → schemas.md 开始
  • 添加认证:plugins.md → hooks.md → authentication.md
  • 提升性能:schemas.md → serialization.md → performance.md
  • 搭建测试:routes.md → testing.md
  • 推进生产:logging.md → configuration.md → deployment.md

资料提供了一个最小可运行的 Fastify 服务器快速上手示例:

import Fastify from 'fastify'

const app = Fastify({ logger: true })

app.get('/health', async (request, reply) => {
  return { status: 'ok' }
})

const start = async () => {
  await app.listen({ port: 3000, host: '0.0.0.0' })
}
start()

核心原则

  • 封装:Fastify 的插件系统提供自动封装能力
  • Schema 优先:为校验和序列化定义 schema
  • 性能:Fastify 针对速度做了优化,应正确使用其特性
  • Async/await:所有处理器和钩子都支持异步函数
  • 最小依赖:优先使用 Fastify 内置特性和官方插件

适用场景与限制

该技能适用于 Fastify 后端与 REST API 的开发、配置和调试,覆盖从入门、认证、性能、测试到生产部署的多种场景。关于具体收费、价格、支持平台或实际使用效果,资料中暂未提供。