FastifyAPI开发技能Skill fastify

Fastify API开发技能是专门用于构建高性能Node.js后端API的专家级技能。该技能提供Fastify框架的全面支持,包括插件配置、生命周期钩子管理、JSON Schema验证、序列化优化和TypeScript集成。适用于开发高并发、低延迟的Web服务、微服务架构和RESTful API,特别强调性能优化和代码可维护性。关键词:Fastify、Node.js、高性能API、微服务、JSON Schema验证、TypeScript、插件开发、后端优化、RESTful API、Web服务开发。

后端开发 0 次安装 0 次浏览 更新于 2/26/2026

名称: fastify 描述: Fastify插件、钩子、验证、序列化和性能优化模式。 允许工具: 读取、写入、编辑、Bash、Glob、Grep

Fastify 技能

为使用Fastify构建高性能API提供专家级协助。

能力

  • 使用插件配置Fastify
  • 实现生命周期管理的钩子
  • 设置JSON Schema验证
  • 为性能优化序列化
  • 使用TypeScript构建类型安全的API
  • 创建可复用的插件

使用场景

在以下情况时调用此技能:

  • 构建高性能API
  • 实现模式验证
  • 创建自定义插件
  • 优化JSON序列化
  • TypeScript集成

输入参数

参数 类型 是否必需 描述
routePrefix 字符串 路由前缀
validation 布尔值 添加JSON Schema验证
plugins 数组 要使用的插件

模式

应用设置

// src/app.ts
import Fastify, { FastifyInstance } from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import swagger from '@fastify/swagger';
import swaggerUi from '@fastify/swagger-ui';

import { usersRoutes } from './routes/users';
import { authRoutes } from './routes/auth';
import { errorHandler } from './plugins/error-handler';

export async function buildApp(): Promise<FastifyInstance> {
  const app = Fastify({
    logger: {
      level: process.env.LOG_LEVEL || 'info',
      transport: process.env.NODE_ENV !== 'production'
        ? { target: 'pino-pretty' }
        : undefined,
    },
    ajv: {
      customOptions: {
        removeAdditional: 'all',
        coerceTypes: true,
        useDefaults: true,
      },
    },
  });

  // 安全插件
  await app.register(helmet);
  await app.register(cors, {
    origin: process.env.CORS_ORIGIN || true,
    credentials: true,
  });
  await app.register(rateLimit, {
    max: 100,
    timeWindow: '1分钟',
  });

  // 文档
  await app.register(swagger, {
    openapi: {
      info: {
        title: 'API文档',
        version: '1.0.0',
      },
      components: {
        securitySchemes: {
          bearerAuth: {
            type: 'http',
            scheme: 'bearer',
          },
        },
      },
    },
  });
  await app.register(swaggerUi, {
    routePrefix: '/docs',
  });

  // 自定义插件
  await app.register(errorHandler);

  // 路由
  await app.register(authRoutes, { prefix: '/api/auth' });
  await app.register(usersRoutes, { prefix: '/api/users' });

  // 健康检查
  app.get('/health', async () => ({
    status: '正常',
    timestamp: new Date().toISOString(),
  }));

  return app;
}

带模式验证的路由

// src/routes/users.ts
import { FastifyPluginAsync } from 'fastify';
import { Type, Static } from '@sinclair/typebox';
import { UsersService } from '../services/users.service';

const UserSchema = Type.Object({
  id: Type.String(),
  name: Type.String(),
  email: Type.String({ format: 'email' }),
  role: Type.Union([Type.Literal('user'), Type.Literal('admin')]),
  createdAt: Type.String({ format: 'date-time' }),
});

const CreateUserSchema = Type.Object({
  name: Type.String({ minLength: 1 }),
  email: Type.String({ format: 'email' }),
  password: Type.String({ minLength: 8 }),
  role: Type.Optional(Type.Union([Type.Literal('user'), Type.Literal('admin')])),
});

const UpdateUserSchema = Type.Partial(CreateUserSchema);

const PaginationSchema = Type.Object({
  page: Type.Optional(Type.Number({ minimum: 1, default: 1 })),
  limit: Type.Optional(Type.Number({ minimum: 1, maximum: 100, default: 10 })),
  search: Type.Optional(Type.String()),
});

type User = Static<typeof UserSchema>;
type CreateUser = Static<typeof CreateUserSchema>;
type UpdateUser = Static<typeof UpdateUserSchema>;
type Pagination = Static<typeof PaginationSchema>;

export const usersRoutes: FastifyPluginAsync = async (fastify) => {
  const service = new UsersService();

  fastify.get<{ Querystring: Pagination }>('/', {
    schema: {
      tags: ['users'],
      querystring: PaginationSchema,
      response: {
        200: Type.Object({
          data: Type.Array(UserSchema),
          meta: Type.Object({
            total: Type.Number(),
            page: Type.Number(),
            limit: Type.Number(),
          }),
        }),
      },
    },
    preHandler: [fastify.authenticate],
  }, async (request) => {
    return service.findAll(request.query);
  });

  fastify.get<{ Params: { id: string } }>('/:id', {
    schema: {
      tags: ['users'],
      params: Type.Object({ id: Type.String() }),
      response: { 200: UserSchema },
    },
    preHandler: [fastify.authenticate],
  }, async (request, reply) => {
    const user = await service.findById(request.params.id);
    if (!user) {
      return reply.status(404).send({ error: '用户未找到' });
    }
    return user;
  });

  fastify.post<{ Body: CreateUser }>('/', {
    schema: {
      tags: ['users'],
      body: CreateUserSchema,
      response: { 201: UserSchema },
    },
    preHandler: [fastify.authenticate, fastify.authorize(['admin'])],
  }, async (request, reply) => {
    const user = await service.create(request.body);
    return reply.status(201).send(user);
  });

  fastify.put<{ Params: { id: string }; Body: UpdateUser }>('/:id', {
    schema: {
      tags: ['users'],
      params: Type.Object({ id: Type.String() }),
      body: UpdateUserSchema,
      response: { 200: UserSchema },
    },
    preHandler: [fastify.authenticate],
  }, async (request) => {
    return service.update(request.params.id, request.body);
  });

  fastify.delete<{ Params: { id: string } }>('/:id', {
    schema: {
      tags: ['users'],
      params: Type.Object({ id: Type.String() }),
    },
    preHandler: [fastify.authenticate, fastify.authorize(['admin'])],
  }, async (request, reply) => {
    await service.delete(request.params.id);
    return reply.status(204).send();
  });
};

钩子和插件

// src/plugins/auth.ts
import { FastifyPluginAsync, FastifyRequest } from 'fastify';
import fp from 'fastify-plugin';
import jwt from '@fastify/jwt';

declare module 'fastify' {
  interface FastifyInstance {
    authenticate: (request: FastifyRequest) => Promise<void>;
    authorize: (roles: string[]) => (request: FastifyRequest) => Promise<void>;
  }
}

declare module '@fastify/jwt' {
  interface FastifyJWT {
    payload: { id: string; email: string; role: string };
    user: { id: string; email: string; role: string };
  }
}

const authPlugin: FastifyPluginAsync = async (fastify) => {
  await fastify.register(jwt, {
    secret: process.env.JWT_SECRET!,
  });

  fastify.decorate('authenticate', async (request: FastifyRequest) => {
    await request.jwtVerify();
  });

  fastify.decorate('authorize', (roles: string[]) => {
    return async (request: FastifyRequest) => {
      await request.jwtVerify();
      if (!roles.includes(request.user.role)) {
        throw fastify.httpErrors.forbidden('权限不足');
      }
    };
  });
};

export default fp(authPlugin, {
  name: 'auth-plugin',
});

// src/plugins/error-handler.ts
import { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';

const errorHandler: FastifyPluginAsync = async (fastify) => {
  fastify.setErrorHandler((error, request, reply) => {
    fastify.log.error(error);

    if (error.validation) {
      return reply.status(400).send({
        error: '验证错误',
        details: error.validation,
      });
    }

    const statusCode = error.statusCode || 500;
    const message = statusCode === 500 && process.env.NODE_ENV === 'production'
      ? '内部服务器错误'
      : error.message;

    return reply.status(statusCode).send({ error: message });
  });
};

export default fp(errorHandler, {
  name: 'error-handler',
});

自定义钩子

// 生命周期钩子
fastify.addHook('onRequest', async (request, reply) => {
  request.startTime = Date.now();
});

fastify.addHook('onResponse', async (request, reply) => {
  const duration = Date.now() - request.startTime;
  request.log.info({ duration }, '请求完成');
});

fastify.addHook('onSend', async (request, reply, payload) => {
  // 在发送前修改响应
  return payload;
});

最佳实践

  • 使用JSON Schema进行验证
  • 利用TypeBox处理TypeScript模式
  • 使用fastify-plugin创建可复用插件
  • 使用钩子处理横切关注点
  • 启用模式序列化以提高性能

目标流程

  • 高性能API开发
  • Node.js微服务
  • API开发
  • 后端优化