Query D1 from Hono (Hono에서 D1 쿼리하기)
이 문서는 Hono 웹 프레임워크에서 D1 데이터베이스를 쿼리하는 방법을 설명해요.
출처: 문서
본문
Hono는 API 우선(API-first) 애플리케이션을 만들기 위한 빠른 웹 프레임워크로, Workers와 Pages를 일급(first-class)으로 지원해요.
Workers를 사용할 때:
- Wrangler 설정 파일을 구성해 D1 데이터베이스를 Worker에 바인딩했는지 확인하세요.
- Hono의
Context↗︎ 매개변수를 통해 D1 데이터베이스에 접근할 수 있어요: 바인딩 ↗︎은context.env에 노출돼요. 이름이DB인 바인딩을 구성했다면c.env.DB를 통해 D1 Workers Binding API 메서드에 접근할 수 있어요. - Cloudflare Workers ↗︎에 대한 Hono 문서를 참고하세요.
Pages Functions를 사용한다면:
- D1 데이터베이스를 Pages Function에 바인딩하세요.
- 로컬에서 개발할 때
wrangler dev에--d1 BINDING_NAME=DATABASE_ID플래그를 전달하세요.BINDING_NAME은 코드에서 호출하는 이름과 일치해야 하고,DATABASE_ID는 Wrangler 설정 파일에 정의된database_id와 일치해야 해요. 예:--d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx. - 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);