Agent Skills by ALSEL
Anthropic Claudeソフトウェア開発⭐ リポ 0品質スコア 50/100

fastify

本番環境向けFastify(TypeScript)の実装パターンを提供するスキルです。スキーマバリデーション、プラグイン構成、型付きルート、エラーハンドリング、セキュリティ強化、ロギング、`inject`を使ったテスト、グレースフルシャットダウンまでを網羅します。Fastifyを用いた堅牢なAPIサーバー構築時に活用できます。

description の原文を見る

Production Fastify (TypeScript) patterns: schema validation, plugins, typed routes, error handling, security hardening, logging, testing with inject, and graceful shutdown

SKILL.md 本文

Fastify (TypeScript) - Production Backend フレームワーク

概要

Fastify は、JSON スキーマ検証、カプセル化されたプラグイン、優れた開発者体験を中心に構築された高性能な Node.js ウェブフレームワークです。TypeScript では、Fastify を Type Provider (Zod または TypeBox) と組み合わせることで、ランタイム検証と静的型付けを一致させることができます。

クイックスタート

最小サーバー

正解: 型付きレスポンスを持つ基本的なサーバー

import Fastify from "fastify";

const app = Fastify({ logger: true });

app.get("/health", async () => ({ status: "ok" as const }));

await app.listen({ host: "0.0.0.0", port: 3000 });

間違い: listen を await せずにサーバーを起動

app.listen({ port: 3000 });
console.log("started"); // 起動と出力が競合し、バインド失敗が隠される

スキーマ検証 + Type Provider

Fastify は JSON スキーマ経由でリクエスト/レスポンスを検証します。Type Provider を使用して型の重複を避けます。

Zod provider (フルスタック TypeScript に推奨)

正解: Zod スキーマが検証と型を駆動

import Fastify from "fastify";
import { z } from "zod";
import { ZodTypeProvider } from "fastify-type-provider-zod";

const app = Fastify({ logger: true }).withTypeProvider<ZodTypeProvider>();

const Query = z.object({ q: z.string().min(1) });

app.get(
  "/search",
  { schema: { querystring: Query } },
  async (req) => {
    return { q: req.query.q };
  },
);

await app.listen({ port: 3000 });

TypeBox provider (OpenAPI + パフォーマンスに推奨)

正解: TypeBox スキーマ

import Fastify from "fastify";
import { Type } from "@sinclair/typebox";
import { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";

const app = Fastify({ logger: true }).withTypeProvider<TypeBoxTypeProvider>();

const Params = Type.Object({ id: Type.String({ minLength: 1 }) });
const Reply = Type.Object({ id: Type.String() });

app.get(
  "/users/:id",
  { schema: { params: Params, response: { 200: Reply } } },
  async (req) => ({ id: req.params.id }),
);

await app.listen({ port: 3000 });

プラグインアーキテクチャ (カプセル化)

プラグインを使用して関心事を分離し、テスト可能にします (認証、DB、ルート)。

正解: ルートプラグイン

import type { FastifyPluginAsync } from "fastify";

export const usersRoutes: FastifyPluginAsync = async (app) => {
  app.get("/", async () => [{ id: "1" }]);
  app.get("/:id", async (req) => ({ id: (req.params as any).id }));
};

正解: プレフィックス付きで登録

app.register(usersRoutes, { prefix: "/api/v1/users" });

エラーハンドリング

予期しない失敗を集中管理し、安定したエラー形式を返します。

正解: setErrorHandler

app.setErrorHandler((err, req, reply) => {
  req.log.error({ err }, "request failed");
  reply.status(500).send({ error: "internal" as const });
});

セキュリティ強化 (ベースライン)

標準的なセキュリティプラグインを追加し、ペイロード制限を強制します。

正解: Helmet + CORS + レート制限

import helmet from "@fastify/helmet";
import cors from "@fastify/cors";
import rateLimit from "@fastify/rate-limit";

await app.register(helmet);
await app.register(cors, { origin: false });
await app.register(rateLimit, { max: 100, timeWindow: "1 minute" });

グレースフルシャットダウン

SIGINT/SIGTERM でHTTP サーバーと下流クライアント (DB、キュー) を閉じます。

正解: シグナル時に閉じる

const close = async (signal: string) => {
  app.log.info({ signal }, "shutting down");
  await app.close();
  process.exit(0);
};

process.on("SIGINT", () => void close("SIGINT"));
process.on("SIGTERM", () => void close("SIGTERM"));

テスト (Fastify inject)

ポートをバインドせずにインメモリでルートをテストします。

正解: inject リクエスト

import Fastify from "fastify";
import { describe, it, expect } from "vitest";

describe("health", () => {
  it("returns ok", async () => {
    const app = Fastify();
    app.get("/health", async () => ({ status: "ok" as const }));

    const res = await app.inject({ method: "GET", url: "/health" });
    expect(res.statusCode).toBe(200);
    expect(res.json()).toEqual({ status: "ok" });
  });
});

デシジョンツリー

Fastify vs Express

  • Fastify はスキーマベースの検証、予測可能なプラグイン、高いスループットが必要な場合に推奨します。
  • Express は最小限のミドルウェアと最大限のエコシステム親和性が必要な場合に推奨します。

Zod vs TypeBox

  • Zod はコードベースが既に Zod で標準化されている場合に推奨します (フォーム、tRPC、共有型)。
  • TypeBox は OpenAPI 生成とパフォーマンスが重要な検証に推奨します。

アンチパターン

  • リクエスト検証をスキップします。スキーマで境界に検証を追加します。
  • すべてを main.ts に登録します。ルートと依存関係をプラグインに分離します。
  • 生のエラーオブジェクトを返します。安定したエラー形式を返し、詳細をログに記録します。

リソース

ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ

詳細情報

作者
bobmatnyc
リポジトリ
bobmatnyc/claude-mpm-skills
ライセンス
MIT
最終更新
不明

Source: https://github.com/bobmatnyc/claude-mpm-skills / ライセンス: MIT

本サイトは GitHub 上で公開されているオープンソースの SKILL.md ファイルをクロール・インデックス化したものです。 各スキルの著作権は原作者に帰属します。掲載に問題がある場合は info@alsel.co.jp または /takedown フォームよりご連絡ください。
原作者: bobmatnyc · bobmatnyc/claude-mpm-skills · ライセンス: MIT