[A-00233] Typescript 1000本ノック (1)

typescript学習のため、1000本ノックシリーズを作成しました。

簡単なAPIを作って学習したいと思います。

RuntimeはBunを使用し、FrameworkはHonoを使用します。

下記のコマンドでプロジェクトを作成します。

bun create hono@latest rest-api

プロンプトにてパッケージ構成等を決定します。下記のとおりにします。

create-hono version 0.15.3
✔ Using target directory … rest-api
? Which template do you want to use? bun
? Do you want to install project dependencies? yes
? Which package manager do you want to use? bun
✔ Cloning the template
✔ Installing project dependencies
🎉 Copied project files
Get started with: cd rest-api

installコマンドを使用して依存関係(ライブラリ)をインストールしておきます。

cd rest-api
bun install

ディレクトリ構成は下記のとおり

.
├── README.md
├── biome.json
├── bun.lockb
├── command.sh
├── node_modules
│   ├── @types
│   ├── bun-types
│   ├── hono
│   └── undici-types
├── package-lock.json
├── package.json
├── src
│   └── index.ts
├── tree.txt
└── tsconfig.json

7 directories, 9 files

biomeを使用します。brewでインストールしておきます。

brew install biome

biome.jsonを作成するため、初期化コマンドを実行します。

biome init

次にbiomeを使ってディレクトリ内のファイルをフォーマットします。

biome format --write

次にbunで簡単なAPIを実行します。

import { Hono } from "hono";

const app = new Hono();

app.get("/", (c) => {
  return c.text("Hello Hono!");
});

export default app;
user@usernoMacBook-Pro rest-api % bun run dev
$ bun run --hot src/index.ts
Started server http://localhost:3000
user@usernoMacBook-Pro rest-api % curl http://localhost:3000/
Hello Hono!%  

とりあえず動くところまで確認できたので次にAPIをカスタムしてきます。

import { Hono } from "hono";
import { serveStatic } from 'hono/bun';

const app = new Hono();

app.use('/static/*', serveStatic({ root: './'}))
app.use('/favicon.ico', serveStatic({ path: './favicon.ico'}))
app.get("/", (c) => {  return c.text("Hello Hono!"); });
app.get("/hello", (c) => c.text('You can access: /static/hello.txt'))
app.get('*', serveStatic({path: './static/fallback.txt'}))

export default {
  port: 8080,
  fetch: app.fetch,
}

上記を動かしてみるとstatic以下のtxtファイルにもアクセスできるようになります。

ついでにテストコードも作ります。

import { describe, expect, it } from 'bun:test'
import app from './src'

describe('My first test', () => {
    it('Should return 200 Response', async () => {
        const req = new Request('http://localhost/')
        const res = await app.fetch(req)
        expect(res.status).toBe(200)
    })
})
bun test index.test.ts

・Appendix

参考文献はこちら

https://hono-ja.pages.dev/docs/getting-started/bun

https://qiita.com/DS27/items/b0b235a769ae43974185

https://biomejs.dev/ja/guides/getting-started

https://biomejs.dev/ja/guides/big-projects

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

*