diff --git a/src/services/helper.ts b/src/services/helper.ts new file mode 100644 index 0000000..8963b87 --- /dev/null +++ b/src/services/helper.ts @@ -0,0 +1,14 @@ +/** + * Shared helper utilities for domain services. + */ + +import { getRequestContext } from "../context.ts"; +import type { OpenProjectClient } from "../client/api-client.ts"; + +/** + * Resolves an OpenProjectClient instance. + * Prefers an explicitly passed client; falls back to the ambient RequestContext. + */ +export function resolveClient(client?: OpenProjectClient): OpenProjectClient { + return client ?? getRequestContext().client; +} diff --git a/tests/services.test.ts b/tests/services.test.ts new file mode 100644 index 0000000..c51e73a --- /dev/null +++ b/tests/services.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from "bun:test"; +import { resolveClient } from "../src/services/helper.ts"; +import { OpenProjectClient } from "../src/client/api-client.ts"; +import { runWithContext, type RequestContext } from "../src/context.ts"; + +describe("Domain Services Helper", () => { + test("resolveClient returns explicit client if provided", () => { + const customClient = new OpenProjectClient({ + baseUrl: "http://example.com", + apiKey: "custom-key", + }); + const result = resolveClient(customClient); + expect(result).toBe(customClient); + }); + + test("resolveClient falls back to getRequestContext().client when omitted", () => { + const ambientClient = new OpenProjectClient({ + baseUrl: "http://example.com", + apiKey: "ambient-key", + }); + const context: RequestContext = { + client: ambientClient, + isReadOnly: false, + }; + + runWithContext(context, () => { + const result = resolveClient(); + expect(result).toBe(ambientClient); + }); + }); + + test("resolveClient throws error when called without client and outside context", () => { + expect(() => resolveClient()).toThrow("No active RequestContext found"); + }); +});