feat: add OpenAI client wrapper

This commit is contained in:
2026-06-11 10:01:45 +01:00
parent 9d209d5a6b
commit ae61b4ce72
2 changed files with 56 additions and 0 deletions
+17
View File
@@ -1 +1,18 @@
// OpenAI API client wrapper.
import OpenAI from "openai";
/**
* Create an OpenAI SDK client from the loaded config.
* @param {object} config - Config object from loadConfig()
* @param {string} config.openaiApiKey - Required. The OpenAI API key.
* @returns {OpenAI} The configured OpenAI SDK client instance.
*/
export function createOpenAIClient(config) {
if (!config?.openaiApiKey) {
throw new Error("Missing config.openaiApiKey.");
}
return new OpenAI({
apiKey: config.openaiApiKey,
});
}
+39
View File
@@ -0,0 +1,39 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const MockClient = vi.fn(function (opts) {
this.apiKey = opts?.apiKey;
});
// Mock the OpenAI SDK — Vitest hoists vi.mock automatically.
vi.mock("openai", () => ({ default: MockClient }));
const { createOpenAIClient } = await import("../../src/openai/client.js");
describe("createOpenAIClient", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("creates OpenAI client with supplied apiKey", () => {
const config = { openaiApiKey: "sk-test-key" };
const client = createOpenAIClient(config);
expect(MockClient).toHaveBeenCalledTimes(1);
expect(MockClient).toHaveBeenCalledWith({ apiKey: "sk-test-key" });
expect(client.apiKey).toBe("sk-test-key");
});
it("throws when openaiApiKey is missing", () => {
const config = {};
expect(() => createOpenAIClient(config)).toThrow("Missing config.openaiApiKey.");
expect(MockClient).not.toHaveBeenCalled();
});
it("throws when openaiApiKey is empty string", () => {
const config = { openaiApiKey: "" };
expect(() => createOpenAIClient(config)).toThrow("Missing config.openaiApiKey.");
expect(MockClient).not.toHaveBeenCalled();
});
});