Closed15

ブログサイトを作ろう

itaosanitaosan

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
itaosanitaosan

package.json に scripts を追加

{
  "scripts": {
    "start": "bun run index.ts"
  }
}
itaosanitaosan

Hono のインストール

bun add hono
bun add -d @cloudflare/workers-types wrangler

一瞬で終わった

itaosanitaosan

scripts変更

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

index.ts変更

import { Hono } from "hono";

const app = new Hono();

const body = figlet.textSync("Bun!");

app.get("/", (c) => c.text(body));

export default app;

itaosanitaosan

wrangler.toml作成

name = "bun-hono"
compatibility_date = "2023-01-01"
itaosanitaosan
  • 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レコード出てきた

itaosanitaosan

HonoからD1にアクセス

型定義のインポートが必要?

import { D1Database } from "@cloudflare/workers-types";

type Bindings = {
  DB: D1Database
}

const app = new Hono<{ Bindings: Bindings }>()

動かないからいったんここまで

itaosanitaosan

初心に戻り、D1のサンプルを動かしてみる
https://developers.cloudflare.com/d1/examples/d1-and-hono/

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

http://127.0.0.1:8787/api/beverages
にアクセスすると、レコードの内容が出てきた

デプロイ

最初にwranglerログイン

wrangler login

DB作成 & 動作確認

wrangler d1 execute d1testdb  --file=./schema.sql

wrangler d1 execute d1testdb   --command='SELECT * FROM Customers'

deploy

npx wrangler deploy

動いた

itaosanitaosan

honoで動かしてみる

プロジェクト作成

npm create hono@latest hono-test

cloudflare-workers選択

さっきのd1testdbからschema.sqlやwrangler.tomlコピー

https://developers.cloudflare.com/d1/examples/d1-and-hono/
の内容からテーブル名などを変えて動かす

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にクローズされました