文档索引
在以下地址获取完整文档索引:/d1/llms.txt
在进一步探索之前,使用此文件来发现所有可用的页面。
构建一个员工名录应用
最后更新:2026年2月2日|复制为 Markdown|查看 Markdown 原文|Agent setup
在本教程中,你将学习如何使用 D1 构建一个员工名录。该应用将允许用户访问组织中员工的信息,并赋予管理员在应用内直接添加新员工的能力。为此,你首先需要设置一个 D1 数据库以无缝管理数据,然后你将使用 HonoX 框架 ↗︎ 和 Cloudflare Pages 来开发和部署你的应用。
先决条件
在继续本教程之前,请确保你具备以下条件:
如果你现在不想进行设置,可以在 GitHub 上查看完整的代码 ↗︎。
1. 安装 HonoX
在本教程中,你将使用 HonoX ↗︎ 来构建你的应用,它是一个用于创建全栈网站和 Web API 的元框架。要在你的项目中使用 HonoX,请运行 hono-create 命令。
要开始,请运行以下命令:
npm create hono@latest
在设置过程中,系统会要求你为项目目录提供一个名称并选择一个模板。在进行选择时,请选择 x-basic 模板。
2. 初始化你的 HonoX 应用
项目设置完成后,你可以看到如下所示生成的文件列表。这是 HonoX 应用的典型项目结构:
.
├── app
│ ├── global.d.ts // global type definitions
│ ├── routes
│ │ ├── _404.tsx // not found page
│ │ ├── _error.tsx // error page
│ │ ├── _renderer.tsx // renderer definition
│ │ ├── about
│ │ │ └── [name].tsx // matches `/about/:name`
│ │ └── index.tsx // matches `/`
│ └── server.ts // server entry file
├── package.json
├── tsconfig.json
└── vite.config.ts
该项目包括应用代码、路由和服务器设置的目录,以及用于包管理、TypeScript 和 Vite 的配置文件。
3. 创建一个数据库
要为你的项目创建一个数据库,请使用 Cloudflare CLI 工具 Wrangler,它支持用于 D1 数据库操作的 wrangler d1 命令。使用以下命令创建一个名为 staff-directory 的新数据库:
npx wrangler d1 create staff-directory
创建数据库后,你需要在 Wrangler 配置文件中设置一个绑定,以将你的数据库与你的应用集成。
此绑定使你的应用能够与 Cloudflare 资源(例如 D1 数据库、KV 命名空间和 R2 存储桶)进行交互。要配置此绑定,请在你的项目根目录中创建一个 Wrangler 文件,并输入基本的设置信息:
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "staff-directory",
// Set this to today's date
"compatibility_date": "2026-10-13"
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "staff-directory"
# Set this to today's date
compatibility_date = "2026-10-13"
接下来,将数据库绑定详情添加到你的 Wrangler 文件中。这涉及指定一个绑定名称(在本例中为 DB),它将在你的应用中用于引用该数据库,以及你在创建数据库时提供的 database_name 和 database_id:
{
"d1_databases": [
{
"binding": "DB",
"database_name": "staff-directory",
"database_id": "f495af5f-dd71-4554-9974-97bdda7137b3"
}
]
}
[[d1_databases]]
binding = "DB"
database_name = "staff-directory"
database_id = "f495af5f-dd71-4554-9974-97bdda7137b3"
你现在已经配置好了你的应用,可以通过命令行或直接在代码库中访问并操作你的 D1 数据库。
你还需要调整 vite.config.js 中的 Vite 配置文件。添加以下配置设置,以确保 Vite 已正确设置,从而在本地环境中与 Cloudflare 绑定一起工作:
import adapter from "@hono/vite-dev-server/cloudflare";
export default defineConfig(({ mode }) => {
if (mode === "client") {
return {
plugins: [client()],
};
} else {
return {
plugins: [
honox({
devServer: {
adapter,
},
}),
pages(),
],
};
}
});
4. 与 D1 交互
要与你的 D1 数据库交互,你可以直接使用 wrangler d1 execute 命令来执行 SQL 命令:
wrangler d1 execute staff-directory --command "SELECT name FROM sqlite_schema WHERE type ='table'"
上述命令允许你直接从命令行运行查询或操作。
对于诸如初始数据填充或批处理之类的操作,你可以传入一个包含你的命令的 SQL 文件。要做到这一点,请在你的项目根目录中创建一个 schema.sql 文件,并将你的 SQL 查询插入该文件:
CREATE TABLE locations (
location_id INTEGER PRIMARY KEY AUTOINCREMENT,
location_name VARCHAR(255) NOT NULL
);
CREATE TABLE departments (
department_id INTEGER PRIMARY KEY AUTOINCREMENT,
department_name VARCHAR(255) NOT NULL
);
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
position VARCHAR(255) NOT NULL,
image_url VARCHAR(255) NOT NULL,
join_date DATE NOT NULL,
location_id INTEGER REFERENCES locations(location_id),
department_id INTEGER REFERENCES departments(department_id)
);
INSERT INTO locations (location_name) VALUES ('London, UK'), ('Paris, France'), ('Berlin, Germany'), ('Lagos, Nigeria'), ('Nairobi, Kenya'), ('Cairo, Egypt'), ('New York, NY'), ('San Francisco, CA'), ('Chicago, IL');
INSERT INTO departments (department_name) VALUES ('Software Engineering'), ('Product Management'), ('Information Technology (IT)'), ('Quality Assurance (QA)'), ('User Experience (UX)/User Interface (UI) Design'), ('Sales and Marketing'), ('Human Resources (HR)'), ('Customer Support'), ('Research and Development (R&D)'), ('Finance and Accounting');
上述查询将创建三个表:Locations、Departments 和 Employees。要使用初始数据填充这些表,请使用 INSERT INTO 命令。在使用这些命令准备好你的模式文件后,你可以将其应用到 D1 数据库。为此,请使用 --file 标志来指定要执行的模式文件:
wrangler d1 execute staff-directory --file=./schema.sql
要在本地执行该模式并将数据填充到你的本地目录中,请为上述命令传入 --local 标志。
5. 创建 SQL 语句
在按照前面步骤设置好你的 D1 数据库并配置好 Wrangler 文件后,你的数据库可以通过 DB 绑定在代码中访问。这使你能够通过准备并执行 SQL 语句来直接与数据库交互。在接下来的步骤中,你将学习如何使用此绑定来执行常见的数据库操作,例如检索数据和插入新记录。
从数据库检索数据
export const findAllEmployees = async (db: D1Database) => {
const query = `
SELECT employees.*, locations.location_name, departments.department_name
FROM employees
JOIN locations ON employees.location_id = locations.location_id
JOIN departments ON employees.department_id = departments.department_id
`;
const { results } = await db.prepare(query).run();
const employees = results;
return employees;
};
将数据插入数据库
export const createEmployee = async (db: D1Database, employee: Employee) => {
const query = `
INSERT INTO employees (name, position, join_date, image_url, department_id, location_id)
VALUES (?, ?, ?, ?, ?, ?)`;
const results = await db
.prepare(query)
.bind(
employee.name,
employee.position,
employee.join_date,
employee.image_url,
employee.department_id,
employee.location_id,
)
.run();
const employees = results;
return employees;
};
有关应用中使用的所有查询的完整列表,请参阅代码库中的 db.ts ↗︎ 文件。
6. 开发 UI
该应用使用 hono/jsx 进行渲染。你可以在 app/routes/_renderer.tsx 中使用 JSX 渲染中间件设置一个 Renderer,作为你应用的入口点:
import { jsxRenderer } from 'hono/jsx-renderer'
import { Script } from 'honox/server'
export default jsxRenderer(({ children, title }) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{title}</title>
<Script src="/app/client.ts" async />
</head>
<body>{children}</body>
</html>
)
})
在定义 TypeScript 全局类型定义的 global.d.ts 文件中添加前面定义的绑定,以确保整个应用中的类型一致性:
declare module "hono" {
interface Env {
Variables: {};
Bindings: {
DB: D1Database;
};
}
}
此应用使用 Tailwind CSS ↗︎ 进行样式设计。要使用 Tailwind CSS,请参阅 TailwindCSS 文档 ↗︎,或按照 GitHub 上提供的步骤 ↗︎ 进行操作。
要显示员工列表,请从你的 db.ts 文件中调用 findAllEmployees 函数,并在 routes/index.tsx 文件中调用它。该文件中的 createRoute() 函数充当一个辅助函数,用于定义处理不同 HTTP 方法(如 GET、POST、PUT 或 DELETE)的路由。
import { css } from 'hono/css'
import { createRoute } from 'honox/factory'
import Counter from '../islands/counter'
const className = css`
font-family: sans-serif;
`
export default createRoute((c) => {
const name = c.req.query('name') ?? 'Hono'
return c.render(
<div class={className}>
<h1>Hello, {name}!</h1>
<Counter />
</div>,
{ title: name }
)
})
该文件中现有的代码包含一个使用 Counter 组件的占位符。你应该将这一部分替换为以下代码块:
import { createRoute } from 'honox/factory'
import type { FC } from 'hono/jsx'
import type { Employee } from '../db'
import { findAllEmployees, findAllDepartments, findAllLocations } from '../db'
const EmployeeCard: FC<{ employee: Employee }> = ({ employee }) => {
const { employee_id, name, image_url, department_name, location_name } = employee;
return (
<div className="max-w-sm bg-white border border-gray-200 rounded-lg shadow-md">
<a href={`/employee/${employee_id}`}>
<img className="bg-indigo-600 p-4 rounded-t-lg" src={image_url} alt={name} />
//...
</a>
</div>
);
};
export const GET = createRoute(async (c) => {
const employees = await findAllEmployees(c.env.DB)
const locations = await findAllLocations(c.env.DB)
const departments = await findAllDepartments(c.env.DB)
return c.render(
<section className="flex-grow">
<h1 className="mb-4 text-3xl font-extrabold text-gray-900 dark:text-white md:text-5xl lg:text-6xl mt-12">
<span className="text-transparent bg-clip-text bg-gradient-to-r to-blue-600 from-sky-400">{`Directory `}</span>
</h1>
//...
</section>
<section className="flex flex-wrap -mx-4">
{employees.map((employee) => (
<div className="w-full sm:w-1/2 md:w-1/3 lg:w-1/4 px-2 mb-4">
<EmployeeCard employee={employee} />
</div>
))}
</section>
</section>
)
})
该代码片段演示了如何从 db.ts 文件导入 findAllEmployees、findAllLocations 和 findAllDepartments 函数,以及如何使用绑定 c.env.DB 来调用这些函数。借助这些,你可以在页面上检索并显示获取到的数据。
添加员工
使用 export POST 路由通过 /admin 页面创建新员工:
import { createRoute } from "honox/factory";
import type { Employee } from "../../db";
import { getFormDataValue, getFormDataNumber } from "../../utils/formData";
import { createEmployee } from "../../db";
export const POST = createRoute(async (c) => {
try {
const formData = await c.req.formData();
const imageFile = formData.get("image_file");
let imageUrl = "";
// TODO: process image url with R2
const employeeData: Employee = {
employee_id: getFormDataValue(formData, "employee_id"),
name: getFormDataValue(formData, "name"),
position: getFormDataValue(formData, "position"),
image_url: imageUrl,
join_date: getFormDataValue(formData, "join_date"),
department_id: getFormDataNumber(formData, "department_id"),
location_id: getFormDataNumber(formData, "location_id"),
location_name: "",
department_name: "",
};
await createEmployee(c.env.DB, employeeData);
return c.redirect("/", 303);
} catch (error) {
return new Response("Error processing your request", { status: 500 });
}
});
将图片存储在 R2 中
在创建新员工的过程中,上传的图片可以在添加到数据库之前存储在 R2 存储桶中。
要将图片存储在 R2 存储桶中:
- 创建一个 R2 存储桶。
- 将图片上传到该存储桶。
- 从存储桶获取该图片的公开 URL。然后此 URL 会被保存在你的数据库中,链接到存储在 R2 存储桶中的图片。
使用 wrangler r2 bucket create 命令创建一个存储桶:
wrangler r2 bucket create employee-avatars
存储桶创建完成后,将 R2 存储桶绑定添加到你的 Wrangler 文件中:
{
"r2_buckets": [
{
"binding": "MY_BUCKET",
"bucket_name": "employee-avatars"
}
]
}
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "employee-avatars"
将 R2 绑定传入 global.d.ts 文件:
declare module "hono" {
interface Env {
Variables: {};
Bindings: {
DB: D1Database;
MY_BUCKET: R2Bucket;
};
}
}
要将上传的图片存储到 R2 存储桶中,你可以使用 R2 提供的 put() 方法。此方法允许你将图片文件上传到你的存储桶:
if (imageFile instanceof File) {
const key = `${new Date().getTime()}-${imageFile.name}`;
const fileBuffer = await imageFile.arrayBuffer();
await c.env.MY_BUCKET.put(key, fileBuffer, {
httpMetadata: {
contentType: imageFile.type || "application/octet-stream",
},
});
console.log(`File uploaded successfully: ${key}`);
imageUrl = `https://pub-8d936184779047cc96686a631f318fce.r2.dev/${key}`;
}
在 GitHub 上查看 ↗︎ 以获取完整的代码库。
7. 部署你的 HonoX 应用
在应用准备好部署后,你可以使用 Wrangler 构建项目并将其部署到 Cloudflare 网络。通过运行 wrangler whoami 命令确保你已登录到你的 Cloudflare 账户。如果你尚未登录,Wrangler 将提示你通过创建一个 API 密钥来登录,你可以使用该密钥自动从你的计算机发出经过身份验证的请求。
成功登录后,确认你的 Wrangler 文件的配置与下方代码块类似:
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "staff-directory",
// Set this to today's date
"compatibility_date": "2026-10-13",
"r2_buckets": [
{
"binding": "MY_BUCKET",
"bucket_name": "employee-avatars"
}
],
"d1_databases": [
{
"binding": "DB",
"database_name": "staff-directory",
"database_id": "f495af5f-dd71-4554-9974-97bdda7137b3"
}
]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "staff-directory"
# Set this to today's date
compatibility_date = "2026-10-13"
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "employee-avatars"
[[d1_databases]]
binding = "DB"
database_name = "staff-directory"
database_id = "f495af5f-dd71-4554-9974-97bdda7137b3"
运行 wrangler deploy 将你的项目部署到 Cloudflare。部署后,你可以通过访问为你提供的已部署 URL 来测试你的应用是否正常工作。你的浏览器应显示你创建的基础前端应用。如果你的数据库中没有填充任何数据,请前往 /admin 页面添加新员工,这应该会在你的主页返回一个新员工。
结论
在本教程中,你构建了一个员工名录应用,用户可以在其中查看组织内的所有员工。请参阅 Staff directory 仓库 ↗︎ 以获取完整的源代码。
