メインコンテンツまでスキップ

Hono Client

Zelt は Hono の hc クライアント用の型安全なクライアント型(AppType)を生成します。IDE の自動補完付きで完全な型安全 API 呼び出しが可能です。

概要

@zeltjs/openapi パッケージは、コントローラーのシグネチャから AppType を生成します。この型を Hono の hc クライアントと組み合わせることで:

  • リクエストパラメーターとレスポンスボディの完全な TypeScript 推論
  • API エンドポイントの IDE 自動補完
  • API 呼び出しのコンパイル時型チェック

インストール

pnpm add @zeltjs/openapi

設定

プロジェクトルートに zelt.config.ts を作成します:

import { defineConfig } from '@zeltjs/openapi';

export default defineConfig({
controllers: ['./src/**/*.controller.ts'],
dist: './generated',
tsconfig: './tsconfig.json',
});

AppType の生成

pnpm zelt-openapi build

<dist>/app.gen.tsAppType が生成されます。

生成される app.gen.ts

// THIS FILE IS GENERATED BY @zeltjs/openapi. DO NOT EDIT.
import type { Route, BuildAppType } from '@zeltjs/openapi';
import type { HelloController } from '../src/controllers/hello.controller';

export type AppType = BuildAppType<[
Route<'GET', '/hello/:name', typeof HelloController.prototype.greet>,
Route<'POST', '/hello', typeof HelloController.prototype.create>,
]>;

AppType の使い方

型安全な API クライアント

import { hc } from 'hono/client';
import type { AppType } from './generated/app.gen';

const client = hc<AppType>('https://api.example.com');

// 完全な型付け - IDE の自動補完と型チェック
const response = await client.hello[':name'].$get({
param: { name: 'world' },
});

if (response.ok) {
const data = await response.json();
// data は { message: string } として型付けされる
console.log(data.message);
}

型安全なクライアントでのテスト

import { hc } from 'hono/client';
import { describe, it, expect } from 'vitest';
import { app } from './app';
import type { AppType } from './generated/app.gen';

describe('Hello API', () => {
const client = hc<AppType>('http://localhost', {
fetch: (input, init) => app.fetch(new Request(input, init)),
});

it('should return greeting', async () => {
const res = await client.hello[':name'].$get({
param: { name: 'world' },
});

expect(res.status).toBe(200);
const body = await res.json();
expect(body.message).toBe('Hello, world!');
});
});

仕組み

  1. 静的解析 — ビルド時にコントローラーメソッドのシグネチャを解析
  2. 型抽出 — TypeScript の型からリクエスト/レスポンス型を抽出
  3. コード生成 — 型レベル計算を使用して AppType を生成

生成された AppType は、コントローラーメソッドを Hono のルート型にマッピングし、hc クライアントがパラメーターとレスポンス型を自動推論できるようにします。