hono-api-scaffolder
Cloudflare Workers 向けの Hono API ルートを自動生成します。ルートファイル、ミドルウェア、型付きバインディング、Zod バリデーション、エラーハンドリング、および API_ENDPOINTS.md ドキュメントを出力します。cloudflare-worker-builder または vite-flare-starter でプロジェクトをセットアップした後、API ルートの追加・エンドポイントの作成・API ドキュメントの生成が必要な際に使用してください。
description の原文を見る
Scaffold Hono API routes for Cloudflare Workers. Produces route files, middleware, typed bindings, Zod validation, error handling, and API_ENDPOINTS.md documentation. Use after a project is set up with cloudflare-worker-builder or vite-flare-starter, when you need to add API routes, create endpoints, or generate API documentation.
SKILL.md 本文
Hono API Scaffolder
既存の Cloudflare Workers プロジェクトに構造化された API ルートを追加します。このスキルはプロジェクトシェルが存在した後(cloudflare-worker-builder または vite-flare-starter 経由)に実行され、ルートファイル、ミドルウェア、およびエンドポイントドキュメントを生成します。
ワークフロー
ステップ 1: エンドポイントを収集
API が何を必要とするかを決定します。ユーザーに質問するか、プロジェクト説明から推測します。エンドポイントをリソースでグループ化します:
Users: GET /api/users, GET /api/users/:id, POST /api/users, PUT /api/users/:id, DELETE /api/users/:id
Posts: GET /api/posts, GET /api/posts/:id, POST /api/posts, PUT /api/posts/:id
Auth: POST /api/auth/login, POST /api/auth/logout, GET /api/auth/me
ステップ 2: ルートファイルを作成
リソースグループごとに 1 ファイル。assets/route-template.ts のテンプレートを使用します:
// src/routes/users.ts
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
import type { Env } from '../types'
const app = new Hono<{ Bindings: Env }>()
// GET /api/users
app.get('/', async (c) => {
const db = c.env.DB
const { results } = await db.prepare('SELECT * FROM users').all()
return c.json({ users: results })
})
// GET /api/users/:id
app.get('/:id', async (c) => {
const id = c.req.param('id')
const user = await db.prepare('SELECT * FROM users WHERE id = ?').bind(id).first()
if (!user) return c.json({ error: 'Not found' }, 404)
return c.json({ user })
})
// POST /api/users
const createUserSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
})
app.post('/', zValidator('json', createUserSchema), async (c) => {
const body = c.req.valid('json')
// ... insert logic
return c.json({ user }, 201)
})
export default app
ステップ 3: ミドルウェアを追加
プロジェクト要件に基づいて assets/middleware-template.ts から追加します:
Auth ミドルウェア — 認証が必要なルートを保護します:
import { createMiddleware } from 'hono/factory'
import type { Env } from '../types'
export const requireAuth = createMiddleware<{ Bindings: Env }>(async (c, next) => {
const token = c.req.header('Authorization')?.replace('Bearer ', '')
if (!token) return c.json({ error: 'Unauthorized' }, 401)
// Validate token...
await next()
})
CORS — Hono のビルトインを使用します:
import { cors } from 'hono/cors'
app.use('/api/*', cors({ origin: ['https://example.com'] }))
ステップ 4: ルートを配線
メインエントリーポイントにすべてのルートグループをマウントします:
// src/index.ts
import { Hono } from 'hono'
import type { Env } from './types'
import users from './routes/users'
import posts from './routes/posts'
import auth from './routes/auth'
import { errorHandler } from './middleware/error-handler'
const app = new Hono<{ Bindings: Env }>()
// Global error handler
app.onError(errorHandler)
// Mount routes
app.route('/api/users', users)
app.route('/api/posts', posts)
app.route('/api/auth', auth)
// Health check
app.get('/api/health', (c) => c.json({ status: 'ok' }))
export default app
ステップ 5: 型を作成
// src/types.ts
export interface Env {
DB: D1Database
KV: KVNamespace // if needed
R2: R2Bucket // if needed
API_SECRET: string // secrets
}
ステップ 6: API_ENDPOINTS.md を生成
すべてのエンドポイントをドキュメント化します。フォーマットについては references/endpoint-docs-template.md を参照してください:
## POST /api/users
Create a new user.
- **Auth**: Required (Bearer token)
- **Body**: `{ name: string, email: string }`
- **Response 201**: `{ user: User }`
- **Response 400**: `{ error: string, details: ZodError }`
キーパターン
Zod バリデーション
@hono/zod-validator でリクエストボディを常にバリデートします:
import { zValidator } from '@hono/zod-validator'
app.post('/', zValidator('json', schema), async (c) => {
const body = c.req.valid('json') // fully typed
})
インストール: pnpm add @hono/zod-validator zod
エラーハンドリング
assets/error-handler.ts の標準エラーハンドラーを使用します:
export const errorHandler = (err: Error, c: Context) => {
console.error(err)
return c.json({ error: err.message }, 500)
}
API ルートは JSON エラーを返す必要があり、リダイレクトではありません。 fetch() はリダイレクトを自動的にフォローしため、クライアントが HTML を JSON として解析しようとします。
RPC 型安全性
Worker とクライアント間のエンドツーエンド型安全性のために:
// Worker: export the app type
export type AppType = typeof app
// Client: use hc (Hono Client)
import { hc } from 'hono/client'
import type { AppType } from '../worker/src/index'
const client = hc<AppType>('https://api.example.com')
const res = await client.api.users.$get() // fully typed
ルートグループ対単一ファイル
| プロジェクトサイズ | 構造 |
|---|---|
| 10 未満のエンドポイント | すべてのルートを含む単一の index.ts |
| 10~30 エンドポイント | リソースごとのルートファイル(routes/users.ts) |
| 30 以上のエンドポイント | ルートファイル + 共有ミドルウェア + 型付きコンテキスト |
リファレンスファイル
| 内容 | 読むファイル |
|---|---|
| Hono パターン、ミドルウェア、RPC | references/hono-patterns.md |
| API_ENDPOINTS.md フォーマット | references/endpoint-docs-template.md |
アセット
| ファイル | 目的 |
|---|---|
assets/route-template.ts | Zod 付きの CRUD スターターロートファイル |
assets/middleware-template.ts | Auth ミドルウェアテンプレート |
assets/error-handler.ts | 標準 JSON エラーハンドラー |
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- jezweb
- リポジトリ
- jezweb/claude-skills
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/jezweb/claude-skills / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。