Cloudflare D1 Database

D1 je SQLite-kompatibilná edge databáza od Cloudflare. Prístupná cez Workers binding, volá sa zo Server Actions.

CRUD — Záznamy

Žiadne záznamy. Pridaj prvý!
lib/db.ts — D1 binding helper
import { getCloudflareContext } from "@opennextjs/cloudflare";

export function getDB(): D1Database {
  return (getCloudflareContext().env as Env).DB;
}
app/d1-database/actions.ts — Server Actions
"use server";
import { getDB } from "@/lib/db";
import { revalidatePath } from "next/cache";

export async function createItem(formData: FormData) {
  const name = formData.get("name") as string;
  const db = getDB();
  await db.prepare("INSERT INTO items (name) VALUES (?)")
    .bind(name).run();
  revalidatePath("/d1-database");
}

export async function listItems() {
  const db = getDB();
  const { results } = await db
    .prepare("SELECT * FROM items ORDER BY id DESC")
    .all();
  return results;
}

Nastavenie

1. Vytvor D1 databázu:

wrangler d1 create showcase-db

2. Skopíruj database_id do wrangler.toml

3. Aplikuj schema:

npm run db:migrate:local

4. Spusti Cloudflare dev server:

npm run preview