💽

cloudflare pages の functions で D1を使う方法

2023/10/15に公開
2

普段workersを使っていて、移行したらあれ?と思ったので。

ポイント

Pagesはwrangler.tomlを参照しない

公式ドキュメントのどこに書かれていたか忘れてしまったけど、Pagesはwrangler.tomlを参照しません。
wrangler.tomlにBindingsを書いたのになかなか反映されなくて悩みました。

PagesのBindingsに手順が書かれている通り、WebGUIでポチポチ設定します。
https://developers.cloudflare.com/pages/platform/functions/bindings/

サンプルコード

上記WebGUIでのポチポチを行った上でのサンプルコード。
Honoを普段使っているので、Hono前提ですが以下のような感じ。

import { Hono } from "hono";
import { handle } from "hono/cloudflare-pages";
import { D1QB, FetchTypes } from "workers-qb";

type Env = {
  Bindings: {
    DB: D1Database;
  };
};

const app = new Hono<Env>().basePath("/api");

// Page向け表示
app.get("/list", async (c) => {
  const qb = new D1QB(c.env.DB);

  const fetched = await qb
    .fetchAll({
      tableName: "example",
      fields: ["*"],
      orderBy: {
        created_at: "DESC",
      },
      limit: 5,
    })
    .execute();

  return c.json({
    json: fetched.results,
  });
});

所感

type Env = {
  Bindings: {
    DB: D1Database;
  };
};

上記のコードがポイントだったんだけど、こういう書き方するんだとよいうドキュメントは見つけられず、いろいろなコードを見てこうかもと思って書いた記憶。
TypeScriptに慣れていると、なんとなく思いついて書けるものなんだろうか。

Discussion

rocchoroccho

記事ありがとうございます。
同じ境遇でして
wrangler参照しないのに、ローカル開発可能でしたか?