SvelteKit ↗ は、Svelte のフロントエンドフレームワークと Vite を組み合わせ、サーバー側の機能とレンダリングを備えたフルスタックフレームワークです。SvelteKit から D1 にクエリするには、D1 データベースへのバインディングを持つ サーバーエンドポイント ↗ を設定します。
D1 にクエリできる、新しい SvelteKit サイトを Cloudflare Pages に用意する手順は次のとおりです。
- SvelteKit ガイド と、Svelte の Cloudflare adapter ↗ を参照します。
- SvelteKit プロジェクト内に Cloudflare adapter をインストールします:
npm i -D @sveltejs/adapter-cloudflare。 - D1 データベースを Pages Function にバインド します。
- ローカル開発では、
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 adapter を 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>"],
},
}),
},
};