使用wrangler创建hono和D1的Worker

以下内容参考了

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
posted on 2024-07-17 18:17  项希盛  阅读(147)  评论(0编辑  收藏  举报