Hands-on Lab
It’s time to put your new skills to the test! In this lab, you will replace the in-memory array in your Task Manager API with a real D1 database.
Objective
Section titled “Objective”- Define the
tasktable schema using Drizzle. - Generate and apply migrations to your local D1 database.
- Rewrite the
GET /api/tasksandPOST /api/tasksendpoints to use the database.
Part 1: Define the Schema
Section titled “Part 1: Define the Schema”Create a new file src/db/schema.ts (or similar path). Define a task table with the following columns:
id(text, primary key)title(text, not null)isCompleted(integer/boolean, default false)createdAt(integer/timestamp)
Part 2: Run Migrations
Section titled “Part 2: Run Migrations”- Ensure your
drizzle.config.tsandwrangler.jsonare configured correctly. - Run the command to generate migrations.
- Run the command to apply migrations to your local database.
Part 3: Connect API
Section titled “Part 3: Connect API”Open your src/index.ts.
- Initialize the Drizzle client using
c.env.DB. - GET /api/tasks: Replace the mock data return with a
db.select()query. - POST /api/tasks: Replace the array push with a
db.insert()query.
💡 Click for Code Hints
Schema Definition:
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
export const tasks = sqliteTable("tasks", { id: text("id").primaryKey(), title: text("title").notNull(), isCompleted: integer("is_completed", { mode: "boolean" }).default(false), createdAt: integer("created_at", { mode: "timestamp" }).default(new Date()),});API Implementation:
import { drizzle } from "drizzle-orm/d1";import { tasks } from "./db/schema";
app.get("/api/tasks", async (c) => { const db = drizzle(c.env.DB); const result = await db.select().from(tasks); return c.json(result);});Verification
Section titled “Verification”-
Start your server Run
bun run dev. -
Create a Task Use Postman or curl to send a POST request to
/api/tasks.Terminal window curl -X POST http://localhost:8787/api/tasks \-H "Content-Type: application/json" \-d '{"title": "Learn Drizzle"}' -
Restart the Server Stop the server (Ctrl+C) and start it again. This proves data persistence!
-
Get Tasks Send a GET request. You should see the task you created, even after the restart.
Terminal window curl http://localhost:8787/api/tasks
Next Steps
Section titled “Next Steps”Congratulations! You have successfully added a persistence layer to your application. In the next module, we will look at how to secure our API with Authentication.