All files / src/lib do-dispatch.ts

100% Statements 6/6
100% Branches 3/3
100% Functions 2/2
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                    34x 34x                                         33x 33x 33x 33x    
/**
 * Helpers to dispatch a Worker-level HTTP request to the room's Durable
 * Object. Keeps the route layer free of `env.ROOM.get(idFromName(…))`
 * boilerplate and makes it trivial to stub `ROOM` in route tests.
 */
import { encodeRoom } from './room-name.ts';
import type { Env } from '../env.ts';
 
/** Return the DO stub for `room`, keyed by its legacy-encoded form. */
export function roomStub(env: Env, room: string): DurableObjectStub {
  const id = env.ROOM.idFromName(encodeRoom(room));
  return env.ROOM.get(id);
}
 
/**
 * Fetch against the DO using the `/_do/*` protocol. Callers pass the path
 * (starting with `/_do/…`) and optional method/body; a fake host
 * (`https://do.local`) is supplied so the DO's URL constructor works.
 *
 * The caller's `room` is always appended as `?name=<encoded>` so the DO
 * can self-identify for the D1 rooms-index mirror (Phase 5.1). DOs are
 * addressed by an opaque id hashed from `encodeRoom(room)`; the DO has
 * no other way to learn its own room name. We append rather than
 * replace any existing query because `path` may already carry one
 * (e.g. `/_do/ping?name=foo` used by unit tests).
 */
export async function doFetch(
  env: Env,
  room: string,
  path: string,
  init: RequestInit = {},
): Promise<Response> {
  const stub = roomStub(env, room);
  const sep = path.includes('?') ? '&' : '?';
  const url = `https://do.local${path}${sep}name=${encodeURIComponent(room)}`;
  return stub.fetch(url, init);
}