INTEGRITY Dokumentace

Durable Objects

Objekty

Durable Objects, které chcete přidat do prostředí, zadejte takto:

const mf = new Miniflare({
	modules: true,
	script: `
  export class Object1 {
    async fetch(request) {
      ...
    }
  }
  export default {
    fetch(request) {
      ...
    }
  }
  `,
	durableObjects: {
		// Note Object1 is exported from main (string) script
		OBJECT1: "Object1",
	},
});

Perzistence

Ve výchozím nastavení jsou data Durable Object uložena v paměti. Zachovají se mezi načteními, ale ne mezi různými Miniflare instance. Chcete-li povolit perzistenci do souborového systému, zadejte možnost perzistence Durable Object:

const mf = new Miniflare({
	durableObjectsPersist: true, // Defaults to ./.mf/do
	durableObjectsPersist: "./data", // Custom path
});

Manipulace mimo Workers

Pro účely testování může být užitečné odesílat požadavky na vaše Durable Objects i mimo worker. To můžete provést pomocí getDurableObjectNamespace metoda.

import { Miniflare } from "miniflare";

const mf = new Miniflare({
	modules: true,
	durableObjects: { TEST_OBJECT: "TestObject" },
	script: `
  export class TestObject {
    constructor(state) {
      this.storage = state.storage;
    }

    async fetch(request) {
      const url = new URL(request.url);
      if (url.pathname === "/put") await this.storage.put("key", 1);
      return new Response((await this.storage.get("key")).toString());
    }
  }

  export default {
    async fetch(request, env) {
      const stub = env.TEST_OBJECT.getByName("test");
      return stub.fetch(request);
    }
  }
  `,
});

const ns = await mf.getDurableObjectNamespace("TEST_OBJECT");
const stub = ns.getByName("test");
const doRes = await stub.fetch("http://localhost:8787/put");
console.log(await doRes.text()); // "1"

const res = await mf.dispatchFetch("http://localhost:8787/");
console.log(await res.text()); // "1"

Používání třídy exportované jiným skriptem

Miniflare podporuje script_name možnost pro přístup k Durable Objects exportovaným jinými skripty. To vyžaduje připojení druhého workeru způsobem popsaným v 🔌 Více Workers.