Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / prodigi.ts

1// Thin Prodigi v4 API client. Reads PRODIGI_API_KEY and PRODIGI_API_BASE_URL
2// from the environment. Server-only — never import from a client component.
3
4const DEFAULT_BASE = 'https://api.prodigi.com/v4.0/';
5
6function baseUrl(): string {
7 const raw = process.env.PRODIGI_API_BASE_URL || DEFAULT_BASE;
8 return raw.endsWith('/') ? raw : `${raw}/`;
9}
10
11function apiKey(): string {
12 // When pointed at the sandbox, prefer the sandbox key so the live key is
13 // never clobbered just to run a test — flip PRODIGI_API_BASE_URL alone.
14 const isSandbox = baseUrl().includes('sandbox');
15 const key = isSandbox
16 ? process.env.PRODIGI_API_KEY_SANDBOX || process.env.PRODIGI_API_KEY
17 : process.env.PRODIGI_API_KEY;
18 if (!key) throw new Error('PRODIGI_API_KEY is not set');
19 return key;
20}
21
22export async function prodigiFetch(
23 path: string,
24 init: RequestInit = {},
25): Promise<Response> {
26 const url = new URL(path.replace(/^\//, ''), baseUrl());
27 const headers = new Headers(init.headers);
28 headers.set('X-API-Key', apiKey());
29 if (init.body && !headers.has('Content-Type')) {
30 headers.set('Content-Type', 'application/json');
31 }
32 return fetch(url, { ...init, headers });
33}