Hono

更新:2025-02-15
JavaScript

概要

JavaScriptランタイム「Deno」とwebフレームワーク「Hono」でAPIを作成してみる。

Denoのインストール

公式を参照。
https://docs.deno.com/runtime/

Macの場合
curl -fsSL https://deno.land/install.sh | sh

Edit shell configs to add deno to the PATH? (Y/n) Y

Set up completions?
[x] zsh

exec $SHELL -lで新しいログインシェルを起動してバージョンが確認できれば完了。

/project-dir
deno -V
# deno 2.1.10

プロジェクトの作成

DenoプロジェクトをHonoで初期化。

/project-dir
deno init --npm hono@latest .
/project-dir
⚠️ Do you fully trust npm:create-hono@latest package? Deno will invoke code from it with all permissions. Do you want to continue? [y/n]
> y
create-hono version 0.15.3
Using target directory .
? Which template do you want to use? deno
? Directory not empty. Continue? yes
Cloning the template
# よく分からないが、最後Enter押さないと終わらなかった

実行。

/project-dir
deno run --allow-net main.ts

ローカルサーバが起動してHello Hono!が確認できた。

APIの作成

方角を指定して、対応する四神の名前を返すだけのAPI。

/project-dir/main.ts
import { Hono, Context } from 'hono';
interface FourGods {
north: string;
east: string;
south: string;
west: string;
}
const fourGods: FourGods = {
north: 'Black Tortoise',
east: 'Azure Dragon',
south: 'Vermilion Bird',
west: 'White Tiger'
};
const app = new Hono();
app.get('/north', (c: Context) => {
return c.text(fourGods.north);
});
app.get('/east', (c: Context) => {
return c.text(fourGods.east);
});
app.get('/south', (c: Context) => {
return c.text(fourGods.south);
});
app.get('/west', (c: Context) => {
return c.text(fourGods.west);
});
Deno.serve(app.fetch);

続く...かもね