Fastify
schema、插件、性能。
35 分钟
Fastify
Fastify 以 低开销、JSON Schema 校验、插件封装 著称。若 Express 像「自由拼装」,Fastify 更像 带契约的 HTTP 引擎——适合 API 优先、要自动校验请求体的服务。
学习目标
- 创建 Fastify 应用与路由
- 用 JSON Schema 校验 body / query
- 理解插件注册与
fastify-plugin封装
基本应用
import Fastify from "fastify";
const app = Fastify({ logger: true });
app.get("/health", async () => ({ ok: true }));
app.post("/api/tracks", {
schema: {
body: {
type: "object",
required: ["slug", "title"],
properties: {
slug: { type: "string", minLength: 1 },
title: { type: "string" },
},
},
},
}, async (request) => {
return { id: 1, ...request.body };
});
await app.listen({ port: 3001, host: "0.0.0.0" });
校验失败时 Fastify 自动返回 400,无需手写 if。
与 Express 对照
| Express | Fastify |
|---|---|
app.use(middleware) | app.register(plugin) |
| 手动校验 body | schema 声明式 |
| 默认无结构化日志 | 内置 pino logger |
插件与性能
- 插件:路由、数据库、认证按模块
register,避免全局污染 - 性能:路由表与序列化优化;高 QPS 场景常选 Fastify(细节见 nodejs-advanced-essentials)
- TypeScript:配合
@fastify/type-provider-typebox或 Zod 可进一步类型化(typescript-essentials)
练习
- 把 node-express 的
/api/tracks改写成 Fastify + schema - 开启
logger: true,观察请求日志格式 - 写一个
fastify-plugin封装「请求耗时」钩子
小结
Schema 先行、插件组合、日志内置——Fastify 的 API 服务默认姿势。 下一课 Hono:更轻、更边缘。
加载本节练习…