web/src/utils/fetch-enrich.ts

30 lines · 944 bytes

 1import { error, warn } from './logger';
 2import { safeFetch } from './safe-fetch';
 3import { apiBase, enrichHeaders } from './api-config';
 4
 5interface EnrichOptions {
 6  // Yeah, it's legit got no upstream record, so 404 is correct/expected
 7  missingIsExpected?: boolean;
 8}
 9
10export const fetchEnrich = async <T>(
11  source: string,
12  path: string,
13  subject: string,
14  { missingIsExpected = false }: EnrichOptions = {},
15): Promise<T | null> => {
16  const endpoint = `${apiBase}${path}`;
17  try {
18    const res = await safeFetch(endpoint, { headers: enrichHeaders() });
19    if (res.ok) return (await res.json()) as T;
20    if (res.status !== 404) {
21      error(source, `HTTP ${res.status} for ${subject} (${endpoint})`);
22    } else if (!missingIsExpected) {
23      warn(source, `No upstream record for ${subject} (${endpoint})`);
24    }
25    return null;
26  } catch (err) {
27    error(source, `Network error for ${subject}: ${err}`);
28    return null;
29  }
30};