miniflare icon indicating copy to clipboard operation
miniflare copied to clipboard

A getMiniflareDurableObjectStorage that doesn't start the DO

Open spigaz opened this issue 2 years ago • 0 comments

When you use getMiniflareDurableObjectStorage() it starts the DO before you can access the storage.

That implies that the DO initialization happens before you are able to setup storage to test its initialization.

So @mrbbot suggested this implementation that works great, but a direct getMiniflareDurableObjectDirectStorage(); makes all the sense for these kind of uses cases.

import { Miniflare } from "miniflare";
import { DurableObjectStorage } from "@miniflare/durable-objects";

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

    async fetch(request) {
      return new Response(await this.storage.get("key"));
    }
  }
  `,
});

const objectName = "TEST_OBJECT";
const ns = await mf.getDurableObjectNamespace(objectName);
const id = ns.idFromName("test");
const pluginStorageFactory = mf.getPluginStorage("DurableObjectsPlugin");
const storageKey = `${objectName}:${id.toString()}`;
const innerStorage = await pluginStorageFactory.storage(
  storageKey,
  durableObjectsPersist
);
const storage = new DurableObjectStorage(innerStorage);
await storage.put("key", "value");

const stub = ns.get(id);
const doRes = await stub.fetch("http://localhost:8787");
console.log(await doRes.text()); // "value"

In my use case I ended up using

  // const storage: DurableObjectStorage = await getMiniflareDurableObjectStorage(id);

  // HACK
  const mf = getMiniflare();

  const pluginStorageFactory = mf.getPluginStorage('DurableObjectsPlugin');
  const storageKey = `${'OBJECT_NAME'}:${id.toString()}`;
  const innerStorage = await pluginStorageFactory.storage(storageKey, false);
  const storage = new DurableObjectStorage(innerStorage);

  await storage.put('key', 'value');

spigaz avatar Jun 29 '22 21:06 spigaz