Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

複数の Workers

最終更新 Markdown で表示Agent セットアップ

Miniflare では、同じインスタンスで複数の Workers を実行できます。すべての Workers は、workers オプションで同じ階層に定義できます。

次の例では、service binding を使い、共有の KV 名前空間の値をインクリメントします。

import { Miniflare, Response } from "miniflare";

const message = "The count is ";
const mf = new Miniflare({
	// Options shared between workers such as HTTP and persistence configuration
	// should always be defined at the top level.
	host: "0.0.0.0",
	port: 8787,
	kvPersist: true,

	workers: [
		{
			name: "worker",
			kvNamespaces: { COUNTS: "counts" },
			serviceBindings: {
				INCREMENTER: "incrementer",
				// Service bindings can also be defined as custom functions, with access
				// to anything defined outside Miniflare.
				async CUSTOM(request) {
					// `request` is the incoming `Request` object.
					return new Response(message);
				},
			},
			modules: true,
			script: `export default {
        async fetch(request, env, ctx) {
          // Get the message defined outside
          const response = await env.CUSTOM.fetch("http://host/");
          const message = await response.text();

          // Increment the count 3 times
          await env.INCREMENTER.fetch("http://host/");
          await env.INCREMENTER.fetch("http://host/");
          await env.INCREMENTER.fetch("http://host/");
          const count = await env.COUNTS.get("count");

          return new Response(message + count);
        }
      }`,
		},
		{
			name: "incrementer",
			// Note we're using the same `COUNTS` namespace as before, but binding it
			// to `NUMBERS` instead.
			kvNamespaces: { NUMBERS: "counts" },
			// Worker formats can be mixed-and-matched
			script: `addEventListener("fetch", (event) => {
        event.respondWith(handleRequest());
      })
      async function handleRequest() {
        const count = parseInt((await NUMBERS.get("count")) ?? "0") + 1;
        await NUMBERS.put("count", count.toString());
        return new Response(count.toString());
      }`,
		},
	],
});
const res = await mf.dispatchFetch("http://localhost");
console.log(await res.text()); // "The count is 3"
await mf.dispose();

ルーティング

API の routes でルーティングを有効にできます。構文は 標準のルート構文 です。ポート番号は無視されます。

const mf = new Miniflare({
	workers: [
		{
			scriptPath: "./api/worker.js",
			routes: ["http://127.0.0.1/api*", "api.mf/*"],
		},
	],
});

ホスト名が localhost127.0.0.1 以外の場合、それらのホスト名が localhost に解決されるよう、コンピューターの hosts ファイルを編集する必要があることがあります。Linux と macOS では通常 /etc/hosts です。Windows では C:\Windows\System32\drivers\etc\hosts です。上のルートでは、次のエントリをファイル末尾に追加します。

127.0.0.1 miniflare.test
127.0.0.1 api.mf

あるいは、リクエスト送信時に Host ヘッダーをカスタマイズできます。

# Dispatches to the "api" worker
$ curl "http://localhost:8787/todos/update/1" -H "Host: api.mf"

API を使う場合、Miniflare はリクエストの URL から、どの Worker にディスパッチするかを決めます。

// Dispatches to the "api" worker
const res = await mf.dispatchFetch("http://api.mf/todos/update/1", { ... });

Durable Objects

Miniflare は、他のスクリプトがエクスポートした Durable Objects にアクセスするための script_name オプションをサポートします。詳細は 📌 Durable Objects を参照してください。

役に立ちましたか?