xiaohongshu
xiaohongshu
hono-d1-integration
Use this skill whenever the user wants to design, set up, or refactor Cloudflare D1 database usage in a Hono + TypeScript app running on Cloudflare Workers/Pages, including schema management, bindings, query patterns, and data-access structure.
Full skill instructions
You are a specialized assistant for using Cloudflare D1 as the database layer in a Hono + TypeScript app running on Cloudflare Workers / Pages.
Use this skill to:
c.env.DB)Do not use this skill for:
hono-app-scaffoldhono-r2-integration)If CLAUDE.md exists, obey its rules for D1 usage, directories, naming and migration strategy.
Trigger this skill when the user asks for things like:
Avoid this skill when:
This skill assumes:
The app runs on Cloudflare Workers or Pages Functions.
D1 is configured as a binding in wrangler.toml, e.g.:
[[d1_databases]]
binding = "DB"
database_name = "my_db"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
In code, D1 is available as c.env.DB.
We will type the Env binding and keep DB access explicit and centralized.
This skill works best with a structure like:
src/
app.ts
index.ts
routes/
v1/
users.routes.ts
posts.routes.ts
db/
schema.sql
migrations/
0001_init.sql
0002_add_posts.sql
d1.ts # D1 helpers and typed Env
services/
user.service.ts
post.service.ts
types/
env.d.ts # Env interface with DB binding
Adjust paths to match the project, but keep D1-related files under a db/ or infrastructure/ style folder.
Create a shared Env type for Workers:
// src/types/env.d.ts
export interface Env {
DB: D1Database;
// other bindings e.g. R2, KV, etc.
}
Then in routes/services:
import type { Env } from "../types/env";
export type AppContext = {
Bindings: Env;
};
Usage with Hono:
import { Hono } from "hono";
import type { AppContext } from "./types";
export const app = new Hono<AppContext>();
This ensures c.env.DB is correctly typed.
Create a small helper for D1 access and typed operations:
// src/db/d1.ts
import type { Env } from "../types/env";
export type D1 = D1Database;
export function getDb(env: Env): D1 {
return env.DB;
}
export async function runQuery<T = unknown>(
db: D1,
sql: string,
params: unknown[] = [],
): Promise<T[]> {
const stmt = db.prepare(sql);
const result = await stmt.bind(...params).all<T>();
return result.results ?? [];
}
For single-row helpers:
export async function runOne<T = unknown>(
db: D1,
sql: string,
params: unknown[] = [],
): Promise<T | null> {
const rows = await runQuery<T>(db, sql, params);
return rows[0] ?? null;
}
This skill should:
.bind(...)D1 uses schema.sql and migrations managed via Wrangler.
-- src/db/schema.sql
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
CREATE TABLE IF NOT EXISTS posts (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
title TEXT NOT NULL,
body TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
FOREIGN KEY (user_id) REFERENCES users(id)
);
Migrations are usually created & applied using commands like:
wrangler d1 execute <db_name> --file=src/db/schema.sql --localwrangler d1 migrations create <db_name> <name>wrangler d1 migrations apply <db_name> --localThis skill should:
Design small services using getDb & query helpers.
Example user.service.ts:
// src/services/user.service.ts
import type { Env } from "../types/env";
import { getDb, runOne, runQuery } from "../db/d1";
import { nanoid } from "nanoid"; // if project uses this for IDs
export type User = {
id: string;
email: string;
password_hash: string;
created_at: string;
};
export class UserService {
constructor(private env: Env) {}
private db() {
return getDb(this.env);
}
async createUser(email: string, passwordHash: string): Promise<User> {
const id = nanoid();
const db = this.db();
await db
.prepare("INSERT INTO users (id, email, password_hash) VALUES (?, ?, ?)")
.bind(id, email, passwordHash)
.run();
const user = await runOne<User>(db, "SELECT * FROM users WHERE id = ?", [id]);
if (!user) throw new Error("Failed to load just-created user");
return user;
}
async findByEmail(email: string): Promise<User | null> {
const db = this.db();
return runOne<User>(db, "SELECT * FROM users WHERE email = ?", [email]);
}
async listUsers(): Promise<User[]> {
const db = this.db();
return runQuery<User>(db, "SELECT * FROM users ORDER BY created_at DESC");
}
}
This skill should:
Example: a simple users route using UserService:
// src/routes/v1/users.routes.ts
import { Hono } from "hono";
import type { AppContext } from "../../types";
import { UserService } from "../../services/user.service";
export function usersRoutes() {
const app = new Hono<AppContext>();
app.get("/", async (c) => {
const service = new UserService(c.env);
const users = await service.listUsers();
return c.json(users);
});
app.post("/", async (c) => {
const body = await c.req.json<{ email: string; password: string }>();
// Validate body with a validation skill if present
const service = new UserService(c.env);
// Password hashing is done via auth skill (bcrypt/argon2) – here we assume `passwordHash`
const passwordHash = "TODO"; // placeholder
const user = await service.createUser(body.email, passwordHash);
return c.json(user, 201);
});
return app;
}
This skill should:
env into services (no global state).hono-authentication (e.g., using D1 to fetch user in login).D1 has more limited transaction semantics than full-blown SQL servers.
This skill should:
D1 returns rows as plain JS objects. This skill should:
User, Post, etc.) that match the schema.runQuery<T>) to type results.This skill can suggest:
wrangler d1 with --local for dev.const mockDb: Partial<D1Database> = {
prepare: jest.fn().mockReturnValue({
bind: jest.fn().mockReturnThis(),
all: jest.fn().mockResolvedValue({ results: [] }),
run: jest.fn().mockResolvedValue({}),
}),
};
wrangler d1 to prepare DB before running.When combined with a Hono testing skill, this gives end-to-end coverage.
This skill must:
hono-app-scaffold) convert them into HTTP responses.Example pattern:
try {
// D1 call
} catch (err) {
console.error("D1 query failed:", err);
throw new Error("Database error");
}
The error-handler middleware can then map Error("Database error") to a 500 JSON payload.
For these tasks, rely on this skill to produce a clean, Hono-friendly D1 integration that is typed, bound via the Env, and ready for production on Cloudflare Workers/Pages.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience