본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Query D1 from Hono (Hono에서 D1 쿼리하기)

원문 보기 위키 갱신

이 문서는 Hono 웹 프레임워크에서 D1 데이터베이스를 쿼리하는 방법을 설명해요.

출처: 문서

본문

Hono는 API 우선(API-first) 애플리케이션을 만들기 위한 빠른 웹 프레임워크로, Workers와 Pages를 일급(first-class)으로 지원해요.

Workers를 사용할 때:

Pages Functions를 사용한다면:

  1. D1 데이터베이스를 Pages Function에 바인딩하세요.
  2. 로컬에서 개발할 때 wrangler dev에 --d1 BINDING_NAME=DATABASE_ID 플래그를 전달하세요. BINDING_NAME은 코드에서 호출하는 이름과 일치해야 하고, DATABASE_ID는 Wrangler 설정 파일에 정의된 database_id와 일치해야 해요. 예: --d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx.
  3. Cloudflare Pages ↗︎에 대한 Hono 가이드를 참고하세요.

다음 예시는 Workers 스크립트와 Pages Function 모두에서 DB에 바인딩된 D1 데이터베이스에 접근하는 방법을 보여줘요:

Workers 스크립트:

import { Hono } from "hono";

// This ensures c.env.DB is correctly typed
type Bindings = {
	DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>();

// Accessing D1 is via the c.env.YOUR_BINDING property
app.get("/query/users/:id", async (c) => {
	const userId = c.req.param("id");
	try {
		let { results } = await c.env.DB.prepare(
			"SELECT * FROM users WHERE user_id = ?",
		)
			.bind(userId)
			.run();
		return c.json(results);
	} catch (e) {
		return c.json({ err: "Failed to query user" }, 500);
	}
});

// Export our Hono app: Hono automatically exports a
// Workers 'fetch' handler for you
export default app;

Pages Function:

import { Hono } from "hono";
import { handle } from "hono/cloudflare-pages";

// This ensures c.env.DB is correctly typed
type Bindings = {
	DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>().basePath("/api");

// Accessing D1 is via the c.env.YOUR_BINDING property
app.get("/query/users/:id", async (c) => {
	const userId = c.req.param("id");
	try {
		let { results } = await c.env.DB.prepare(
			"SELECT * FROM users WHERE user_id = ?",
		)
			.bind(userId)
			.run();
		return c.json(results);
	} catch (e) {
		return c.json({ err: "Failed to query user" }, 500);
	}
});

// Export the Hono instance as a Pages onRequest function
export const onRequest = handle(app);