// The swarm name loader: one request however many callers, and a name that is // absent, empty, or failed to load all answer null. Run by `npm test`. import assert from "node:assert/strict"; import { test } from "node:test"; import { createSwarmNameLoader } from "../src/shell/swarm-name.ts"; // A fetch that answers `body` as an ok response, counting its calls. function fetching(body, ok = true) { const f = async (url) => { f.calls.push(url); return { ok, json: async () => body }; }; f.calls = []; return f; } test("the loader answers the configured name", async () => { const f = fetching({ name: "constellation" }); assert.equal(await createSwarmNameLoader(f)(), "constellation"); assert.deepEqual(f.calls, ["/api/swarm"]); }); test("every caller shares one request", async () => { const f = fetching({ name: "constellation" }); const load = createSwarmNameLoader(f); const names = await Promise.all([load(), load(), load()]); assert.deepEqual(names, ["constellation", "constellation", "constellation"]); assert.equal(f.calls.length, 1); }); test("a null, empty or missing name answers null", async () => { for (const body of [{ name: null }, { name: "" }, {}]) { assert.equal(await createSwarmNameLoader(fetching(body))(), null); } }); test("an error response answers null", async () => { assert.equal( await createSwarmNameLoader(fetching({ name: "x" }, false))(), null, ); }); test("a failed request answers null rather than throwing", async () => { const load = createSwarmNameLoader(async () => { throw new Error("offline"); }); assert.equal(await load(), null); }); test("a failed request is remembered, not retried by later callers", async () => { let calls = 0; const load = createSwarmNameLoader(async () => { calls += 1; throw new Error("offline"); }); await load(); await load(); assert.equal(calls, 1); });