// Server-side Go API client. Nitro routes use it so the browser only talks to // this origin and control credentials stay in the Node process. interface ApiErrorEnvelope { error?: { code?: string; message?: string } message?: string statusMessage?: string } export interface ApiRequestOptions { query?: Record method?: 'GET' | 'POST' /** Raw request body, forwarded unchanged (multipart training uploads). */ body?: any headers?: Record /** Attach CONTROL_USER/CONTROL_PASS as Basic auth. */ control?: boolean timeoutMs?: number } const DEFAULT_API_BASE = 'http://localhost:8080' function envValue(...names: string[]): string { for (const name of names) { const value = process.env[name] if (value !== undefined && value !== '') return value } return '' } /** Runtime Go base URL. Reads the env directly so K8s can override the build. */ export function apiBaseUrl(): string { const config = useRuntimeConfig() return ( envValue('NUXT_API_INTERNAL_BASE', 'NUXT_API_BASE', 'NUXT_PUBLIC_API_BASE') || String(config.apiBase ?? '') || DEFAULT_API_BASE ).replace(/\/+$/, '') } /** Mock mode is opt-in via NUXT_USE_MOCK or NUXT_PUBLIC_USE_MOCK (1/true). */ export function isMockMode(): boolean { const config = useRuntimeConfig() const raw = envValue('NUXT_USE_MOCK', 'NUXT_PUBLIC_USE_MOCK') || String(config.useMock ?? '') return raw === '1' || raw.toLowerCase() === 'true' } function controlAuthorization(): string | undefined { const config = useRuntimeConfig() const user = envValue('CONTROL_USER', 'NUXT_CONTROL_USER') || String(config.controlUser ?? '') const pass = envValue('CONTROL_PASS', 'NUXT_CONTROL_PASS') || String(config.controlPass ?? '') if (user && pass) return `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}` const token = envValue('CONTROL_TOKEN', 'NUXT_CONTROL_TOKEN') || String(config.controlToken ?? '') // Go requires Basic today; Bearer is a fallback for a future token-based API. if (token) return `Bearer ${token}` return undefined } function timeoutMs(override?: number): number { if (override && Number.isFinite(override)) return override const configured = Number( envValue('NUXT_API_TIMEOUT_MS') || useRuntimeConfig().apiTimeoutMs, ) return Number.isFinite(configured) && configured > 0 ? configured : 8000 } function upstreamError(error: unknown): never { const err = error as { status?: number statusCode?: number data?: ApiErrorEnvelope message?: string code?: string } const status = err.status ?? err.statusCode if (status && status >= 400 && status < 600) { const message = err.data?.error?.message ?? err.data?.message ?? err.message ?? 'Go API request failed' throw createError({ statusCode: status, statusMessage: message, data: err.data }) } const reason = err.code === 'ETIMEDOUT' ? 'timed out' : 'unreachable' throw createError({ statusCode: 502, statusMessage: `Go API ${reason} at ${apiBaseUrl()}`, }) } /** * Call the Go API and return its JSON body. Non-2xx responses are converted to * H3 errors carrying the upstream status, so the UI sees a real 400/404/503. */ export async function apiRequest(path: string, options: ApiRequestOptions = {}): Promise { const headers: Record = { accept: 'application/json', ...options.headers } if (options.control) { const authorization = controlAuthorization() if (authorization) headers.authorization = authorization } const response = await $fetch .raw(`${apiBaseUrl()}${path}`, { method: options.method ?? 'GET', query: options.query, body: options.body, headers, timeout: timeoutMs(options.timeoutMs), }) .catch((error) => upstreamError(error)) if (response.status >= 400) { const body = response._data as ApiErrorEnvelope | undefined const message = body?.error?.message ?? body?.message ?? `Go API returned ${response.status}` throw createError({ statusCode: response.status, statusMessage: message, data: body }) } return response._data as T } /** Forward a training upload and keep Go's status code for 202/4xx/5xx. */ export async function apiForward( event: import('h3').H3Event, path: string, options: ApiRequestOptions = {}, ): Promise { const headers: Record = { accept: 'application/json', ...options.headers } if (options.control) { const authorization = controlAuthorization() if (authorization) headers.authorization = authorization } const response = await $fetch .raw(`${apiBaseUrl()}${path}`, { method: options.method ?? 'POST', query: options.query, body: options.body, headers, timeout: timeoutMs(options.timeoutMs), }) .catch((error) => upstreamError(error)) setResponseStatus(event, response.status) return response._data as T } /** Validate an enum-like query value before it reaches the Go API. */ export function enumParam( value: unknown, allowed: readonly T[], name: string, fallback?: T, ): T { if (value === undefined || value === '') { if (fallback !== undefined) return fallback throw createError({ statusCode: 400, statusMessage: `${name} is required` }) } const candidate = String(value) as T if (!allowed.includes(candidate)) { throw createError({ statusCode: 400, statusMessage: `Invalid ${name}: ${candidate}. Expected ${allowed.join(' | ')}.`, }) } return candidate } export function sensorParam(value: unknown, fallback = 'hn-stadtgalerie-01'): string { const sensor = value === undefined || value === '' ? fallback : String(value) if (!sensor) throw createError({ statusCode: 400, statusMessage: 'sensor is required' }) return sensor }