Motoki Shakagori (釋迦郡 元気)
今回のお話はベースマキナの事例ではなく*、前職のSpirのものです!!!
ただ、ベースマキナでもプロダクト以外でWorkersを使っています!
export default { async fetch(request, env, ctx) { return new Response("Hello, world!"); }, };
設定ファイルにちょろちょろっと書くだけで本番でもローカル開発時も使える
// service-aというWorkerからservice-bというWorkerを呼び出す場合 { "name": "service-a", "services": [ { "binding": "SERVICE_B", // コードから呼びだすときの名前 "service": "service-b", // デプロイするときにつけた名前 }, ], }
インターフェースはfetchなのでHTTP越しのやりとりにしか見えない*
// index.ts export default { async fetch(request, env) { return await env.SERVICE_B.fetch(request); }, };
* fetch以外のインターフェースを使えるモードもあります
service-a
service-b
// server.ts import { Hono } from "hono"; const app = new Hono() .get("/hello", (c) => c.json({ message: "Hello, World!" })) .get("/dog", (c) => c.json({ face: "" })); export type AppType = typeof app; export default app; // client.ts import { hc } from "hono/client"; import type { AppType } from "./server"; const client = hc<AppType>("http://localhost:8787"); await client.hello.$get().then((res) => res.json()); // { message: string }型 await client.dog.$get().then((res) => res.json()); // { face: string } 型
Service Bindingでも問題なく使える!!!
import { hc } from "hono/client"; import type { AppType } from "./server"; export default { async fetch(request, env) { const _fetch: typeof fetch = (...args) => env.SERVICE_B.fetch(...args); // 本番ではドメインは無視されるが有効なURL文字列を入れないとエラーになる const client = hc<AppType>("http://localhost:8787", { fetch: _fetch }); const res = await client.hello.$get(); const data = await res.json(); return new Response(data.message); }, };
よいCloudflare Workersライフを!