はじめに
表題通りCloudflareWorkers→D1に接続し、CRUD処理を実施する。
準備
プロジェクト作成
~/develop/cloudflare_api$ npm create cloudflare@latest
> npx
> create-cloudflare
using create-cloudflare version 2.23.0
╭ Create an application with Cloudflare Step 1 of 3
│
├ In which directory do you want to create your application?
│ dir ./honod1
│
├ What would you like to start with?
│ category Framework Starter
│
├ Which development framework do you want to use?
│ framework Hono
│
├ Continue with Hono via `npx create-hono@0.10.1 honod1 --template cloudflare-workers --install --pm npm`
│
create-hono version 0.10.1
✔ Using target directory … honod1
✔ Cloning the template
⠏ Installing project dependencies
D1にDB、TBLを作成する
DDLを流してusersテーブルを作成していきます。
schema.sql
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
プロジェクト配下にsqlを配置してください。
wrangler.toml
#:schema node_modules/wrangler/config-schema.json
name = "honod1"
main = "src/index.ts"
compatibility_date = "2024-07-29"
account_id = "XXXXXXXXXXX"
workers_dev = true
[[d1_databases]]
binding = "D1"
database_name = "my_db_d1"
database_id = "XXXXXXXXXXX"
wrangler.tomlを変更し、デプロイできる形式にします。
d1_databasesの中の値を変更してください。
では実際にSQLを流していきましょう。
~/develop/cloudflare_api/honod1 (master)$ npx wrangler d1 execute my_db_d1 --file=./schema.sql --remote
⛅️ wrangler 3.68.0
-------------------
✔ ⚠️ This process may take some time, during which your D1 database will be unavailable to serve queries.
Ok to proceed? … yes
🌀 Executing on remote database my_db_d1 (XXXXXXXXXXXXXXXXX):
🌀 To execute on your local development database, remove the --remote flag from your wrangler command.
Note: if the execution fails to complete, your DB will return to its original state and you can safely retry.
├ 🌀 Uploading XXXXXXXXXXXXXXX.sql
│ 🌀 Uploading complete.
│
🌀 Starting import...
🌀 Processed 1 queries.
🚣 Executed 1 queries in 0.00 seconds (2 rows read, 5 rows written)
Database is currently at bookmark 00000005-00000000-00004de3-
XXXXXXXXXX.
┌────────────────────────┬───────────┬──────────────┬────────────────────┐
│ Total queries executed │ Rows read │ Rows written │ Database size (MB) │
├────────────────────────┼───────────┼──────────────┼────────────────────┤
│ 1 │ 2 │ 5 │ 0.02 │
└────────────────────────┴───────────┴──────────────┴────────────────────┘
上記のコマンドでサーバに作成されたDBにSQLを流す事ができます。
ローカル環境に流したい場合は、npx wrangler d1 execute my_db_d1 --file=./schema.sql
を実行してください。
→これでDBにテーブルが作成されました。
ようやく準備完了しましたね。ではこれからCloudflareWorkersからD1に接続できるようにしていきます。
ローカル環境で実行
では実際に動かしていきましょう。
npm run dev
サーバで実行
まずはサーバにデプロイします。
npm run deploy