| 1 | // D1: https://developers.cloudflare.com/d1/worker-api/ |
| 2 | // |
| 3 | // A guestbook on one D1 database. `env.DB` addresses a cell holding one SQLite |
| 4 | // file with one writer, so when a write resolves it is in the bucket. Scale |
| 5 | // comes from many databases, not one big one: give each tenant its own |
| 6 | // `database_name`. |
| 7 | // |
| 8 | // `batch()`, `withSession()` and `dump()` throw rather than half-work. |
| 9 | const SCHEMA = ` |
| 10 | CREATE TABLE IF NOT EXISTS entries ( |
| 11 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 12 | name TEXT NOT NULL, |
| 13 | message TEXT NOT NULL, |
| 14 | at INTEGER NOT NULL |
| 15 | ); |
| 16 | CREATE INDEX IF NOT EXISTS entries_at ON entries (at DESC); |
| 17 | `; |
| 18 | |
| 19 | // One `exec()` per isolate, not one per request. The statements are |
| 20 | // idempotent, so a racing isolate is harmless. A rejection resets the memo: |
| 21 | // `??=` alone would cache the failed promise, and one transient error would |
| 22 | // then fail every later request in this isolate with the same stale cause. |
| 23 | let ready; |
| 24 | const migrate = (env) => |
| 25 | (ready ??= env.DB.exec(SCHEMA).catch((error) => { |
| 26 | ready = undefined; |
| 27 | throw error; |
| 28 | })); |
| 29 | |
| 30 | export default { |
| 31 | async fetch(request, env) { |
| 32 | await migrate(env); |
| 33 | const url = new URL(request.url); |
| 34 | |
| 35 | if (request.method === "POST") { |
| 36 | const { name, message } = await request.json(); |
| 37 | const written = await env.DB |
| 38 | .prepare("INSERT INTO entries (name, message, at) VALUES (?, ?, ?)") |
| 39 | .bind(name, message, Date.now()) |
| 40 | .run(); |
| 41 | return Response.json({ |
| 42 | id: written.meta.last_row_id, |
| 43 | changes: written.meta.changes, |
| 44 | }, { status: 201 }); |
| 45 | } |
| 46 | |
| 47 | const count = await env.DB |
| 48 | .prepare("SELECT count(*) AS n FROM entries") |
| 49 | .first("n"); |
| 50 | if (url.pathname === "/count") return Response.json({ count }); |
| 51 | |
| 52 | // `all()` copies the whole result set into this Worker, so bound it: |
| 53 | // celld refuses a result set above 100,000 rows. |
| 54 | const { results } = await env.DB |
| 55 | .prepare("SELECT id, name, message, at FROM entries ORDER BY at DESC LIMIT ?") |
| 56 | .bind(20) |
| 57 | .all(); |
| 58 | return Response.json({ count, entries: results }); |
| 59 | }, |
| 60 | }; |