Closed15
ブログサイトを作ろう

1日目
技術スタック
- Cloudflare Workers
- Hono
- D1
で、ブログサイト作ってみよう
参考

Cloudflare Workers サイト作成
- Wokers & Pages
- Create application
- Create Worker

Bun install
curl -fsSL https://bun.sh/install | bash
##Pathの追加
export PATH="~/.bun/bin:$PATH"
bun project作成
mkdir bun-test
cd bun-test
bun init
##一度走らせてみる
bun run index.ts

package.json に scripts を追加
{
"scripts": {
"start": "bun run index.ts"
}
}

Hono のインストール
bun add hono
bun add -d @cloudflare/workers-types wrangler
一瞬で終わった

scripts変更
{
"scripts": {
- "start": "bun run index.ts"
+ "start": "wrangler dev index.ts",
+ "deploy": "wrangler deploy --minify index.ts"
}
}

index.ts変更
import { Hono } from "hono";
const app = new Hono();
const body = figlet.textSync("Bun!");
app.get("/", (c) => c.text(body));
export default app;

wrangler.toml作成
name = "bun-hono"
compatibility_date = "2023-01-01"

bun run start
で、動いた

cloudflareへのDeploy
bun run deploy

jsx-ssrを試す
のフォルダ構成を作るpackage.jsonの内容変更
"scripts": {
"start": "wrangler dev src/index.tsx --live-reload",
"deploy": "wrangler deploy --minify src/index.tsx"
},
--live-reload
つけると、tsx編集したらすぐに反映される。すげえ

- Cloudflare D1作成
bunx wrangler d1 create blog-d1
wrangler.tomlに下記追加
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "blog-d1"
database_id = "XXXXXXXXX"
schema.sql作成
DROP TABLE IF EXISTS Customers;
CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT);
INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name');
ローカルでD1を動かしてみる
scriptsに追加
"scripts": {
"dev": "wrangler dev src/index.tsx --live-reload",
"deploy": "wrangler deploy --minify src/index.tsx",
"localdb": "wrangler d1 execute blog-d1 --local --file=./schema.sql"
},
bun localdb
データがあるか確認
bun wrangler d1 execute <DATABASE_NAME> --local --command='SELECT * FROM Customers'
4レコード出てきた

HonoからD1にアクセス
型定義のインポートが必要?
import { D1Database } from "@cloudflare/workers-types";
type Bindings = {
DB: D1Database
}
const app = new Hono<{ Bindings: Bindings }>()
動かないからいったんここまで

初心に戻り、D1のサンプルを動かしてみる
npm create cloudflare@latest
d1の作成
wrangler d1 create d1testdb
wrangler.tomlに追加
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "d1testdb"
database_id = "999999"
schema.sqlの作成
DROP TABLE IF EXISTS Customers;
CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT);
INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name');
ローカルにDB作成
wrangler d1 execute d1testdb --local --file=./schema.sql
実行確認
wrangler d1 execute d1testdb --local --command='SELECT * FROM Customers'
index.ts書き換え
export interface Env {
// If you set another name in wrangler.toml as the value for 'binding',
// replace "DB" with the variable name you defined.
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env) {
const { pathname } = new URL(request.url);
if (pathname === "/api/beverages") {
// If you did not use `DB` as your binding name, change it here
const { results } = await env.DB.prepare(
"SELECT * FROM Customers WHERE CompanyName = ?"
)
.bind("Bs Beverages")
.all();
return Response.json(results);
}
return new Response(
"Call /api/beverages to see everyone who works at Bs Beverages"
);
},
};
テスト実行
wrangler dev
にアクセスすると、レコードの内容が出てきた
デプロイ
最初にwranglerログイン
wrangler login
DB作成 & 動作確認
wrangler d1 execute d1testdb --file=./schema.sql
wrangler d1 execute d1testdb --command='SELECT * FROM Customers'
deploy
npx wrangler deploy
動いた

honoで動かしてみる
プロジェクト作成
npm create hono@latest hono-test
cloudflare-workers選択
さっきのd1testdbからschema.sqlやwrangler.tomlコピー
の内容からテーブル名などを変えて動かす
import { Hono } from 'hono'
// This ensures c.env.DB is correctly typed
type Bindings = {
DB: D1Database
}
const app = new Hono<{ Bindings: Bindings }>()
// Accessing D1 is via the c.env.YOUR_BINDING property
app.get("/", async (c) => {
try {
let { results } = await c.env.DB.prepare(
"SELECT * FROM Customers WHERE CompanyName = ?"
)
.bind("Bs Beverages")
.all();
return c.json(results)
} catch (e) {
return c.json({err: e}, 500)
}
})
// Export our Hono app: Hono automatically exports a
// Workers 'fetch' handler for you
export default app
デプロイしてみたら動いた
このスクラップは2023/10/02にクローズされました