Communitygithub.com

YepAPI/skills

Express.js 和 Fastify 模式:中间件、路由组织、Zod 验证、错误处理、插件系统、请求生命周期、TypeScript 配置。

skills 是什么?

该技能为使用 Express.js 和 Fastify 构建 Node.js API 的开发者和 AI 代理(如 Claude Code、Cursor、Codex)提供了一套完整的编码规范和模式。它涵盖了从路由组织(按域划分)、输入验证(使用 Zod 库)、到错误处理(集中式错误处理器)和请求生命周期的方方面面。技能特别强调了 TypeScript 的类型安全,为请求和响应提供了泛型支持。对于 Fastify,它深入介绍了插件系统、JSON Schema 验证以及 `fastify-type-provider-zod` 的使用,以实现端到端的类型安全。此外,技能还包含了健康检查端点、优雅关闭等生产环境的实践,并明确指出了常见的不良实践,如将业务逻辑放入路由处理程序或在前端验证后省略后端验证。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/YepAPI/skills/tree/HEAD/skills/express-fastify

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Express & Fastify

规则

  • 按域组织路由:routes/users.ts、routes/orders.ts — 每个资源一个路由器
  • 使用 Zod 验证所有输入:在处理之前解析 req.body、req.params、req.query
  • 集中式错误处理器:Express 中使用 catch-all 中间件,Fastify 中使用 setErrorHandler
  • 返回一致的错误格式:{ error: { code: string, message: string, details?: unknown } }
  • TypeScript:使用泛型类型化请求/响应 — Request<Params, ResBody, ReqBody, Query>
  • 中间件顺序:CORS、body 解析器、认证、速率限制、路由、错误处理器
  • 使用异步路由处理器 — 用错误捕获包装或使用 express-async-errors
  • Fastify:使用插件系统封装路由和装饰器 — fastify.register()
  • Fastify schemas:定义 JSON Schema 或使用 @fastify/type-provider-zod 进行验证 + 序列化
  • 健康检查:GET /health — 返回 200 并包含数据库/Redis 连接状态
  • 优雅关闭:监听 SIGTERM 信号,停止接受新连接,完成正在处理的请求

模式

// Express + Zod 验证
import { Router } from "express";
import { z } from "zod";

const router = Router();
const CreateUserSchema = z.object({ email: z.string().email(), name: z.string().min(1) });

router.post("/users", async (req, res, next) => {
  try {
    const body = CreateUserSchema.parse(req.body);
    const user = await createUser(body);
    res.status(201).json(user);
  } catch (err) { next(err); }
});
// Fastify + Zod 类型提供器
import Fastify from "fastify";
import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "fastify-type-provider-zod";

const app = Fastify().withTypeProvider<ZodTypeProvider>();
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);

app.post("/users", { schema: { body: CreateUserSchema } }, async (req) => {
  return createUser(req.body); // 完全类型化
});

避免

  • 将业务逻辑放在路由处理程序中 — 提取到服务/领域层
  • 忘记 Express 中的异步错误处理 — 未捕获的拒绝会导致进程崩溃
  • 在一个文件中导入所有路由 — 使用 router.use() 或 Fastify 插件来实现模块化
  • 跳过输入验证,因为“前端已经验证了” — 始终在服务器端进行验证

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

YepAPI/skills

WCAG 2.1 AA — semantic HTML, keyboard navigation, screen readers.

YepAPI/skills

Experiment setup, variant splitting, statistical significance, and feature flag integration.

YepAPI/skills

CRUD generators, data tables, user management, role-based access, and bulk operations.

YepAPI/skills

Monitor what ChatGPT and Gemini say about your brand using YepAPI.

YepAPI/skills

Queue workers with BullMQ/Inngest/Trigger.dev, job retries, dead letter queues, concurrency.

YepAPI/skills

Commander.js, interactive prompts with Clack, spinners, colors, config files, exit codes, and npm publishing.

YepAPI/skills

cmdk integration, Cmd+K trigger, fuzzy search, grouped actions, keyboard navigation, and dynamic action registration.

YepAPI/skills

Content planning with trend and sentiment data from YepAPI.

YepAPI/skills

Content calendar, keyword-driven planning, and content briefs.

YepAPI/skills

Theme switching with CSS variables, system preference detection, next-themes, and persistence.

YepAPI/skills

Threaded comments, @mentions, reactions, moderation queue, optimistic UI, and cursor pagination.

YepAPI/skills

Competitive analysis between domains using YepAPI.

YepAPI/skills

Layout grids, KPI cards, data tables with sorting/filtering, sidebar navigation, and responsive breakpoints.

YepAPI/skills

Data encryption — TLS everywhere, AES-256-GCM for PII, bcrypt passwords, encrypted backups.

YepAPI/skills

Chart patterns with Recharts/Nivo/D3, responsive containers, color scales, and accessibility.

YepAPI/skills

Drizzle schema definition, push vs migrate, type-safe queries, relations, transactions, and prepared statements.

YepAPI/skills

Upload handling, resize/compress, CDN delivery, blur placeholders, and next/image patterns.

YepAPI/skills

Local business and Google Maps research using YepAPI.

YepAPI/skills

Cursor-based pagination, IntersectionObserver, virtualized lists with @tanstack/react-virtual, and scroll position restoration.

YepAPI/skills

Chat UI components, streaming responses with AI SDK, context window management, and RAG patterns.

相关技能