跳转到内容
搜索文档

从 SvelteKit 查询 D1

从 SvelteKit 应用查询 D1 数据库。

最后更新 查看 MarkdownAgent 设置

SvelteKit 是一个全栈框架,将 Svelte 前端框架与 Vite 结合,提供服务器端功能和渲染。您可以通过配置带有 D1 数据库绑定的服务器端点从 SvelteKit 查询 D1。

要在 Cloudflare Pages 上设置可查询 D1 的新 SvelteKit 站点:

  1. 请参阅 SvelteKit 指南 和 Svelte 的 Cloudflare 适配器
  2. 在 SvelteKit 项目中安装 Cloudflare 适配器:npm i -D @sveltejs/adapter-cloudflare
  3. 将 D1 数据库绑定到 Pages Function
  4. 在本地开发时,向 wrangler dev 传递 --d1 BINDING_NAME=DATABASE_ID 标志。BINDING_NAME 应与代码中的调用匹配,DATABASE_ID 应与 Wrangler 配置文件中定义的 database_id 匹配:例如 --d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx

以下示例展示如何创建配置为查询 D1 的服务器端点。

  • 绑定在每个端点传递的 platform 参数上可用,通过 platform.env.BINDING_NAME 访问。
  • 使用 SvelteKit 的基于文件的路由,在 src/routes/api/users/+server.ts 中定义的服务器端点在 SvelteKit 应用中可通过 /api/users 访问。

该示例还展示如何在 src/app.d.ts 中配置应用级类型以识别 D1Database 绑定,将 @sveltejs/adapter-cloudflare 适配器导入 svelte.config.js,并配置它应用于所有路由。

import type { RequestHandler } from "@sveltejs/kit";

export async function GET({ request, platform }) {
	try {
		let result = await platform.env.DB.prepare(
			"SELECT * FROM users LIMIT 5",
		).run();
		return new Response(JSON.stringify(result), {
			headers: { "Content-Type": "application/json" },
		});
	} catch (error) {
		return Response.json({ error: "Failed to fetch users" }, {
			status: 500
		});
	}
}
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
	namespace App {
		// interface Error {}
		// interface Locals {}
		// interface PageData {}
		interface Platform {
			env: {
				DB: D1Database;
			};
			context: {
				waitUntil(promise: Promise<any>): void;
			};
			caches: CacheStorage & { default: Cache };
		}
	}
}

export {};
import adapter from "@sveltejs/adapter-cloudflare";

export default {
	kit: {
		adapter: adapter({
			// See below for an explanation of these options
			routes: {
				include: ["/*"],
				exclude: ["<all>"],
			},
		}),
	},
};

这篇文档对您有帮助吗?