Bunではじめる
このガイドでは、Bun上でZeltアプリケーションをゼロから構築する手順を説明します。
前提条件
インストール
bun add @zeltjs/core @zeltjs/adapter-bun
プロジェクト構成
my-app/
├── src/
│ ├── entry/
│ │ ├── controllers/ # HTTPエンドポイント
│ │ └── commands/ # CLIコマンド
│ ├── services/ # ビジネスロジック
│ ├── configs/ # 設定クラス
│ ├── app.ts # アプリケーション定義
│ ├── cli.ts # CLIエントリポイント
│ └── main.ts # HTTPサーバーエントリポイント
├── package.json
└── tsconfig.json
| ディレクトリ | 用途 |
|---|---|
entry/ | 外部向けエントリポイント(HTTP、CLI) |
services/ | ビジネスロジック、DIで注入される |
configs/ | 環境変数と設定 |
Hello World
Step 1: Controllerを作成する
src/entry/controllers/hello.controller.ts を作成します:
@Controller('/hello')
export class HelloController {
@Get('/:name')
greet(req = request()) {
const name = req.pathParam('name');
return { message: `Hello, ${name}!` };
}
}
Step 2: アプリケーションを作成する
src/app.ts を作成します:
export const app = createApp([http({
controllers: [HelloController],
})]);
Step 3: entryを作成する
src/index.ts を作成します:
const bunApp = await onBun(app);
const server = bunApp.http.serve({ port: 3000 });
console.log(`Server running at http://${server.address.hostname}:${server.address.port}`);
onBun() 関数はアプリをBunランタイム用に準備します。返されるオブジェクトには以下が含まれます:
serve(options?)—Bun.serve()を使ってHTTPサーバーを起動しますshutdown()— アプリケーションをgracefulにシャットダウンしますget<T>(Class)— DIコンテナからserviceを解決しますargs— コマンドライン引数(Bun.argv.slice(2))
Step 4: サーバーを起動する
bun run src/index.ts
http://localhost:3000/hello/world にアクセスすると、次のように表示されます:
{ "message": "Hello, world!" }
サーバーオプション
serve() メソッドはportとhostnameのオプションを受け取ります:
const server = bunApp.http.serve({
port: 8080,
hostname: '127.0.0.1',
});
| オプション | デフォルト | 説明 |
|---|---|---|
port | 3000 | 待ち受けるport |
hostname | '0.0.0.0' | バインドするhostname |
コマンドサポート
アプリにcommandが含まれる場合、onBun() はCLI実行のためにcommand機能を commands namespaceの下に保持します:
const bunApp = await onBun(app);
const result = await bunApp.commands.execCommand(['greet', 'world']);
console.log(result.exitCode); // 0 または 1
Warmupオプション
onBun() はデフォルトで即時初期化(warmup: true)を使用します — 全controllerが起動時に解決されます。
遅延初期化(controllerは最初のリクエスト時に解決)にするには:
const bunApp = await onBun(app, { warmup: false });
| オプション | 挙動 | 用途 |
|---|---|---|
warmup: true(デフォルト) | 全controllerが起動時に解決される | 長時間稼働するサーバー |
warmup: false | controllerは最初のリクエスト時に解決される | コールドスタートの最適化 |
次のステップ
- Controllers — ルーティングとHTTPメソッド
- Services — ビジネスロジックと依存性注入
- Commands — CLIコマンド