Closed4

bun + D1 + cloudflare workers, 環境作成

knaka Tech-Blogknaka Tech-Blog

概要

bun環境で、 D1 + cloudflare workersの開発の準備メモとなります

  • cloudflareに、ログインしておきます
knaka Tech-Blogknaka Tech-Blog

環境

  • bun 1.0
  • cloudflare D1
  • cloudflare workers

  • dbName, projectName 仮に下記にしてます

  • db: my-d1

  • project: project1

knaka Tech-Blogknaka Tech-Blog
mkdir project1
cd project1

bun init

bun add -d @cloudflare/workers-types wrangler
bun add -d better-sqlite3

login

bunx wrangler login

d1-create

bunx wrangler d1 create my-d1
  • 成功すると、D1画面にDB作成されます

  • wrangler.toml
name = "project1"
main = "src/index.ts"
compatibility_date = "2023-09-01"
node_compat = true

[vars]
API_KEY = "123"

[[ d1_databases ]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "my-d1"
database_id = "1234"

  • package.json
....

  "scripts": {
    "start": "wrangler dev",
    "deploy": "wrangler publish",
    "test": "vitest"
  }
....


  • src/index.ts

index.ts
export default {
	async fetch(request, env) {
	  const { pathname } = new URL(request.url);
	  console.log(env.DB);
  
	  if (pathname === "/api/cunstomer") {
		const { results } = await env.DB.prepare(
		  "SELECT * FROM Customers WHERE id > ?"
		)
		  .bind(0)
		  .all();
		return Response.json(results);
	  }
	  // …
	  return new Response("Call /api/users to display users over 30 years old");
	},
  };


  • schema.sql
DROP TABLE IF EXISTS Customers;
CREATE TABLE Customers (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  createdAt TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updatedAt TIMESTAMP(3) NULL,
  CompanyName TEXT NOT NULL,
  ContactName TEXT NOT NULL
);

INSERT INTO Customers (CompanyName, ContactName) VALUES ('Alfreds Futterkiste', 'Maria Anders');
INSERT INTO Customers (CompanyName, ContactName) VALUES ('Around the Horn', 'Thomas Hardy');
INSERT INTO Customers (CompanyName, ContactName) VALUES ('Bs Beverages', 'Victoria Ashworth');


local-d1

  • table create:
bunx wrangler d1 execute my-d1 --local --file=./schema.sql

#test
bunx wrangler d1 execute my-d1 --local --command='SELECT * FROM Customers'

D1, table create:

bunx wrangler d1 execute my-d1 --file=./schema.sql

# test
bunx wrangler d1 execute my-d1 --command='SELECT * FROM Customers'

  • dev-server
bun run start

local-http test

curl http://127.0.0.1:8787/api/cunstomer

deploy

bunx wrangler publish
knaka Tech-Blogknaka Tech-Blog
  • package.json
{
  "name": "bun_5d1",
  "module": "src/index.ts",
  "type": "module",
  "devDependencies": {
    "@cloudflare/workers-types": "^4.20230914.0",
    "better-sqlite3": "^8.6.0",
    "bun-types": "latest",
    "wrangler": "^3.9.0"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  },
  "scripts": {
    "start": "wrangler dev",
    "deploy": "wrangler publish",
    "test": "vitest"
  }
}
このスクラップは2023/09/22にクローズされました