| import type { BulkLookupJobDetail, BulkLookupJobSummary } from '../types'; |
|
|
| const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? '/api/pots-shutdown'; |
|
|
| let adminApiKey: string | null = null; |
|
|
| export function setAdminApiKey(value: string) { |
| const trimmed = value.trim(); |
| adminApiKey = trimmed ? trimmed : null; |
| } |
|
|
| export function clearAdminApiKey() { |
| adminApiKey = null; |
| } |
|
|
| export function getAdminApiKey() { |
| return adminApiKey; |
| } |
|
|
| async function request<T>(path: string, init?: RequestInit): Promise<T> { |
| const isAdminRequest = path.startsWith('/admin/') || path.startsWith('/ai/'); |
| const isFormData = init?.body instanceof FormData; |
| const response = await fetch(`${API_BASE_URL}${path}`, { |
| headers: { |
| ...(!isFormData ? { 'Content-Type': 'application/json' } : {}), |
| ...(isAdminRequest && adminApiKey ? { 'X-Admin-Key': adminApiKey } : {}), |
| ...(init?.headers ?? {}), |
| }, |
| ...init, |
| }); |
| if (!response.ok) { |
| throw new Error(`Request failed: ${response.status}`); |
| } |
| return response.json() as Promise<T>; |
| } |
|
|
| function bulkLookupDownloadUrl(id: number): string { |
| const path = `${API_BASE_URL}/bulk-lookup/jobs/${id}/download`; |
| return new URL(path, window.location.origin).toString(); |
| } |
|
|
| export const apiClient = { |
| get: <T,>(path: string) => request<T>(path), |
| post: <T,>(path: string, body?: unknown) => |
| request<T>(path, { |
| method: 'POST', |
| body: body ? JSON.stringify(body) : undefined, |
| }), |
| uploadBulkLookupFile: (file: File): Promise<BulkLookupJobSummary> => { |
| const formData = new FormData(); |
| formData.append('file', file); |
| return request<BulkLookupJobSummary>('/bulk-lookup/jobs', { |
| method: 'POST', |
| body: formData, |
| }); |
| }, |
| listBulkLookupJobs: (): Promise<BulkLookupJobSummary[]> => request<BulkLookupJobSummary[]>('/bulk-lookup/jobs'), |
| getBulkLookupJob: (id: number): Promise<BulkLookupJobDetail> => |
| request<BulkLookupJobDetail>(`/bulk-lookup/jobs/${id}`), |
| bulkLookupDownloadUrl, |
| }; |
|
|