name: Fastify REST API Patterns description: 高性能 Node.js Web框架,内置模式验证、JSON序列化和TypeScript支持。
Fastify REST API Patterns
概览
Fastify 是一个专注于速度和低开销的高性能 Node.js Web框架,特点是内置模式验证和序列化,使开发者能够快速创建生产就绪的API。
Fastify 包含:
- 高性能:比Express快2倍
- JSON模式验证:内置JSON Schema验证
- 快速序列化:优化的JSON序列化
- TypeScript支持:一级TypeScript支持
- 插件系统:可扩展的插件架构
- 低开销:最小的请求开销
为什么这很重要
- 增强性能:Fastify可以通过2-3倍提升API性能
- 降低基础设施成本:更高的吞吐量降低基础设施成本
- 增加开发者体验:内置验证和序列化提升DX
- 减少错误:类型安全验证减少错误
- 改善可扩展性:高性能框架改善可扩展性
核心概念
1. 应用设置
import Fastify from 'fastify'
export async function buildApp(): Promise<FastifyInstance> {
const app = Fastify({
logger: {
level: 'info',
},
})
return app
}
2. 路由
import { FastifyPluginAsync } from 'fastify'
const userRoutes: FastifyPluginAsync = async (fastify) => {
fastify.get('/users', async (request, reply) => {
return { users: [] }
})
fastify.post('/users', async (request, reply) => {
return reply.status(201).send({ success: true })
})
}
export default userRoutes
3. JSON模式验证
const userProperties = {
id: { type: 'string', format: 'uuid' },
email: { type: 'string', format: 'email' },
name: { type: 'string', minLength: 2, maxLength: 100 },
}
export const createUserSchema: FastifySchema = {
body: {
type: 'object',
required: ['email', 'password', 'name'],
properties: {
email: { type: 'string', format: 'email' },
password: { type: 'string', minLength: 8 },
name: { type: 'string', minLength: 2, maxLength: 100 },
},
},
response: {
201: {
type: 'object',
properties: {
success: { type: 'boolean' },
data: {
type: 'object',
properties: userProperties,
},
},
},
},
}
4. 插件
import fp from 'fastify-plugin'
async function databasePlugin(fastify: FastifyInstance) {
const prisma = new PrismaClient()
await prisma.$connect()
fastify.decorate('prisma', prisma)
fastify.addHook('onClose', async (instance) => {
await instance.prisma.$disconnect()
})
}
export default fp(databasePlugin, { name: 'database' })
5. 钩子
钩子类型(按顺序):
- onRequest
- preParsing
- preValidation
- preHandler
- preSerialization
- onSend
- onResponse
export async function authHook(
request: FastifyRequest,
reply: FastifyReply
) {
const authHeader = request.headers.authorization
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new UnauthorizedError('No token provided')
}
const token = authHeader.substring(7)
const payload = await verifyToken(token)
request.user = payload
}
6. 错误处理
export class AppError extends Error {
constructor(
public message: string,
public statusCode: number = 500,
public code?: string
) {
super(message)
this.name = this.constructor.name
}
}
app.setErrorHandler((error: FastifyError, request, reply) => {
request.log.error(error)
const statusCode = error.statusCode || 500
const message = error.message || 'Internal Server Error'
reply.status(statusCode).send({
success: false,
error: {
message,
statusCode,
code: error.code,
},
})
})
7. 认证
import fp from 'fastify-plugin'
import jwt from '@fastify/jwt'
export default fp(async (fastify) => {
await fastify.register(jwt, {
secret: env.JWT_SECRET,
})
})
// 路由中的使用
fastify.get('/protected', {
onRequest: async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
reply.send(err)
}
}
}, async (request) => {
return { message: 'Protected data' }
})
快速开始
-
安装Fastify:
npm install fastify npm install -D typescript @types/node tsx -
创建基本服务器:
import Fastify from 'fastify' const app = Fastify() app.get('/', async (request, reply) => { return { hello: 'world' } }) app.listen({ port: 3000 }) -
添加插件:
npm install @fastify/cors @fastify/helmet @fastify/jwt -
启动服务器:
npx tsx src/server.ts
生产检查清单
- [ ] 使用TypeScript进行类型安全
- [ ] 实施JSON模式验证
- [ ] 使用Fastify钩子处理跨领域问题
- [ ] 实施适当的错误处理
- [ ] 添加认证和授权
- [ ] 使用插件实现可重用功能
- [ ] 实施请求ID跟踪
- [ ] 使用async/await进行异步操作
- [ ] 使用Jest测试端点
- [ ] 使用Swagger文档
- [ ] 添加CORS配置
- [ ] 实施速率限制
- [ ] 使用缓存提高性能
- [ ] 监控性能和错误
- [ ] 优化序列化
- [ ] 使用连接池
反模式
- 不良的JSON模式设计:不要错误地设计JSON模式
- 缺少错误处理:不要未能适当处理错误
- 无请求ID:不要未能跟踪请求ID
- 性能不佳:不要未能优化性能
- 无监控:不要未能监控性能
- 不良的TypeScript:不要错误地使用TypeScript
集成点
- 错误处理:
03-backend-api/error-handling - 验证:
03-backend-api/validation - 中间件:
03-backend-api/middleware - API设计:
01-foundations/api-design - 监控:
14-monitoring-observability