使用wrangler建立hono和D1的Worker

项希盛發表於2024-07-17

以下內容參考了

https://developers.cloudflare.com/d1/get-started/
https://developers.cloudflare.com/d1/examples/d1-and-hono/

1:登入

npx wrangler login

2:建立Worker

npm create cloudflare@latest d1-tutorial

Choose "Hello World" Worker for the type of application.
Select yes to using TypeScript.
Select no to deploying.

3:建立資料庫

npx wrangler d1 create prod-d1-tutorial

4:繫結資料庫

cd d1-tutorial
nano wrangler.toml

在末尾新增

[[d1_databases]]
binding = "DB"
database_name = "prod-d1-tutorial"
database_id = "<unique-ID-for-your-database>"

5:匯入測試資料

將下面程式碼儲存成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');

然後用下面程式碼匯入

npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql

6:安裝依賴庫

npm i hono

7:修改程式碼

echo ''> src/index.ts
nano src/index.ts

貼入下面程式碼

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("/api/beverages/:id", async (c) => {
  const customerID = c.req.param("id");
  try {
    let { results } = await c.env.DB.prepare(
      "SELECT * FROM Customers WHERE CustomerID = ?",
    )
      .bind(customerID)
      .all();
    return c.json(results);
  } catch (e) {
    return c.json({ err: e.message }, 500);
  }
});

// Export our Hono app: Hono automatically exports a
// Workers 'fetch' handler for you
export default app;

8:本地測試程式碼

npm run start

瀏覽器開啟下面網址

localhost:8787/api/beverages/4

9:遠端測試程式碼

npm run deploy

瀏覽器開啟下面網址

https://d1-tutorial.test.workers.dev/api/beverages/4

10:釋出程式碼

npx wrangler publish

相關文章