feat: wire Nitro API to Go, real staffing plan and train proxy
- Replace mock Nitro routes with server-side proxies to the Go API - /plan reads Go /api/staffing; local assumption edits are a labeled preview - /simulate reads base and scenario staffing from Go instead of local multipliers - Route train upload and scenario POST through Nitro with server-only credentials - Keep NUXT_PUBLIC_USE_MOCK=1 as an explicit dev fallback only - Match Go's global-peak flat schedule and add a captured Go parity fixture - Run the web runtime as numeric UID/GID 10001:10001 - Add make check, Gitea CI workflow and a proxy smoke script
This commit is contained in:
1 parent
e8d141ca43
commit
b33e6ff001
33 files changed
+1147
-317
No files matched your search
@@ -1,3 +1,8 @@
|
||||
import type { ContextResponse } from '../../shared/types'
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
import { mockContext } from '../utils/mock-data'
|
||||
|
||||
export default defineEventHandler(() => mockContext)
|
||||
export default defineEventHandler(async () => {
|
||||
if (isMockMode()) return mockContext
|
||||
return apiRequest<ContextResponse>('/api/context')
|
||||
})
|
||||
+23
-25
@@ -1,34 +1,32 @@
|
||||
import { applyScenario } from '../../shared/staffing'
|
||||
import { HORIZONS, SCENARIOS } from '../../shared/types'
|
||||
import type { Horizon, Scenario } from '../../shared/types'
|
||||
import type { ForecastResponse, Horizon, Scenario } from '../../shared/types'
|
||||
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
|
||||
import { getMockForecast } from '../utils/mock-data'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event)
|
||||
const sensor = String(query.sensor ?? 'hn-stadtgalerie-01')
|
||||
const horizon = String(query.horizon ?? '7d') as Horizon
|
||||
const scenario = String(query.scenario ?? 'base') as Scenario
|
||||
const forecast = getMockForecast(sensor)
|
||||
const sensor = sensorParam(query.sensor)
|
||||
const horizon = enumParam<Horizon>(query.horizon, HORIZONS, 'horizon', '7d')
|
||||
const scenario = enumParam<Scenario>(query.scenario, SCENARIOS, 'scenario', 'base')
|
||||
|
||||
if (!forecast) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
|
||||
}
|
||||
if (!HORIZONS.includes(horizon)) {
|
||||
throw createError({ statusCode: 400, statusMessage: `Invalid horizon: ${horizon}` })
|
||||
}
|
||||
if (!SCENARIOS.includes(scenario)) {
|
||||
throw createError({ statusCode: 400, statusMessage: `Invalid scenario: ${scenario}` })
|
||||
if (isMockMode()) {
|
||||
const forecast = getMockForecast(sensor)
|
||||
if (!forecast) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
|
||||
}
|
||||
const points = applyScenario(forecast.points, scenario)
|
||||
const limit = horizon === '15m' ? 1 : horizon === '1h' ? 4 : horizon === '48h' ? 48 : points.length
|
||||
return {
|
||||
...forecast,
|
||||
horizon,
|
||||
scenario,
|
||||
points: points.slice(0, limit),
|
||||
cached: false,
|
||||
}
|
||||
}
|
||||
|
||||
const points = applyScenario(forecast.points, scenario)
|
||||
const limit = horizon === '15m' ? 1 : horizon === '1h' ? 4 : horizon === '48h' ? 48 : points.length
|
||||
|
||||
return {
|
||||
...forecast,
|
||||
horizon,
|
||||
scenario,
|
||||
points: points.slice(0, limit),
|
||||
// The mock is computed locally; it is not a cached fallback from the Go API.
|
||||
cached: false,
|
||||
}
|
||||
return apiRequest<ForecastResponse>('/api/forecast', {
|
||||
query: { sensor, horizon, scenario },
|
||||
})
|
||||
})
|
||||
@@ -1 +1,6 @@
|
||||
export default defineEventHandler(() => ({ ok: true }))
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
|
||||
export default defineEventHandler(async () => {
|
||||
if (isMockMode()) return { ok: true }
|
||||
return apiRequest<{ ok: boolean }>('/api/healthz')
|
||||
})
|
||||
@@ -1,3 +1,8 @@
|
||||
import type { MetaResponse } from '../../shared/types'
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
import { mockMeta } from '../utils/mock-data'
|
||||
|
||||
export default defineEventHandler(() => mockMeta)
|
||||
export default defineEventHandler(async () => {
|
||||
if (isMockMode()) return mockMeta
|
||||
return apiRequest<MetaResponse>('/api/meta')
|
||||
})
|
||||
@@ -1 +1,6 @@
|
||||
export default defineEventHandler(() => ({ ok: true, data: true, model: true }))
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
|
||||
export default defineEventHandler(async () => {
|
||||
if (isMockMode()) return { ok: true, data: true, model: true }
|
||||
return apiRequest<{ ok: boolean; data: boolean; model: boolean }>('/api/readyz')
|
||||
})
|
||||
@@ -1,3 +1,8 @@
|
||||
import type { ScenarioState } from '../../shared/types'
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
import { mockScenario } from '../utils/mock-data'
|
||||
|
||||
export default defineEventHandler(() => mockScenario)
|
||||
export default defineEventHandler(async () => {
|
||||
if (isMockMode()) return mockScenario
|
||||
return apiRequest<ScenarioState>('/api/scenario')
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { SCENARIOS } from '../../shared/types'
|
||||
import type { Scenario, ScenarioDefinition } from '../../shared/types'
|
||||
import type { Scenario, ScenarioDefinition, ScenarioState } from '../../shared/types'
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
import { mockScenario } from '../utils/mock-data'
|
||||
|
||||
let version = mockScenario.version
|
||||
@@ -13,10 +14,21 @@ export default defineEventHandler(async (event) => {
|
||||
statusMessage: 'Invalid scenario. Expected base | sunny-saturday-market | rainy-saturday | weekday-event.',
|
||||
})
|
||||
}
|
||||
version += 1
|
||||
return {
|
||||
version,
|
||||
scenario: body,
|
||||
at: new Date().toISOString(),
|
||||
|
||||
if (isMockMode()) {
|
||||
version += 1
|
||||
return {
|
||||
version,
|
||||
scenario: body,
|
||||
at: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
// Control credentials are attached in the server process, never in the
|
||||
// browser. Go returns 503 until CONTROL_USER/CONTROL_PASS are configured.
|
||||
return apiRequest<ScenarioState>('/api/scenario', {
|
||||
method: 'POST',
|
||||
body,
|
||||
control: true,
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,5 @@
|
||||
import { mockScenarios } from '../utils/mock-data'
|
||||
import { SCENARIO_PRESETS } from '../../shared/scenarios'
|
||||
|
||||
export default defineEventHandler(() => mockScenarios)
|
||||
// Scenario labels are UI metadata, not a Go endpoint. The forecast values and
|
||||
// the scenario enum come from the API.
|
||||
export default defineEventHandler(() => SCENARIO_PRESETS)
|
||||
@@ -1,3 +1,8 @@
|
||||
import type { Sensor } from '../../shared/types'
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
import { mockSensors } from '../utils/mock-data'
|
||||
|
||||
export default defineEventHandler(() => mockSensors)
|
||||
export default defineEventHandler(async () => {
|
||||
if (isMockMode()) return mockSensors
|
||||
return apiRequest<Sensor[]>('/api/sensors')
|
||||
})
|
||||
@@ -1,12 +1,29 @@
|
||||
import type { SeriesResponse } from '../../shared/types'
|
||||
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
|
||||
import { getMockSeries } from '../utils/mock-data'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
const STEPS = ['15m', '1h'] as const
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event)
|
||||
const sensor = String(query.sensor ?? 'hn-stadtgalerie-01')
|
||||
const series = getMockSeries(sensor)
|
||||
if (!series) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
|
||||
const sensor = sensorParam(query.sensor)
|
||||
|
||||
if (isMockMode()) {
|
||||
const series = getMockSeries(sensor)
|
||||
if (!series) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
|
||||
}
|
||||
const step = query.step === '15m' ? '15m' : '1h'
|
||||
return { ...series, step }
|
||||
}
|
||||
const step = query.step === '15m' ? '15m' : '1h'
|
||||
return { ...series, step }
|
||||
|
||||
const step = query.step ? enumParam(query.step, STEPS, 'step') : undefined
|
||||
return apiRequest<SeriesResponse>('/api/series', {
|
||||
query: {
|
||||
sensor,
|
||||
step,
|
||||
from: query.from,
|
||||
to: query.to,
|
||||
},
|
||||
})
|
||||
})
|
||||
+27
-26
@@ -1,37 +1,38 @@
|
||||
import { applyScenario, buildStaffing, planWeekStart } from '../../shared/staffing'
|
||||
import { planDrivers } from '../../shared/insights'
|
||||
import { SCENARIOS, STANDARDS } from '../../shared/types'
|
||||
import type { Scenario, Standard } from '../../shared/types'
|
||||
import type { Scenario, StaffingResponse, Standard } from '../../shared/types'
|
||||
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
|
||||
import { getMockForecast, mockContext, mockDemo } from '../utils/mock-data'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event)
|
||||
const sensor = String(query.sensor ?? 'hn-stadtgalerie-01')
|
||||
const scenario = String(query.scenario ?? 'base') as Scenario
|
||||
const standard = String(query.standard ?? 'standard') as Standard
|
||||
const forecast = getMockForecast(sensor)
|
||||
const sensor = sensorParam(query.sensor)
|
||||
const scenario = enumParam<Scenario>(query.scenario, SCENARIOS, 'scenario', 'base')
|
||||
const standard = enumParam<Standard>(query.standard, STANDARDS, 'standard', 'standard')
|
||||
|
||||
if (!forecast) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
|
||||
}
|
||||
if (!SCENARIOS.includes(scenario)) {
|
||||
throw createError({ statusCode: 400, statusMessage: `Invalid scenario: ${scenario}` })
|
||||
}
|
||||
if (!STANDARDS.includes(standard)) {
|
||||
throw createError({ statusCode: 400, statusMessage: `Invalid standard: ${standard}` })
|
||||
if (isMockMode()) {
|
||||
const forecast = getMockForecast(sensor)
|
||||
if (!forecast) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
|
||||
}
|
||||
const weekStart = planWeekStart(mockDemo.now)
|
||||
const build = buildStaffing({
|
||||
sensor,
|
||||
scenario,
|
||||
standard,
|
||||
points: applyScenario(forecast.points, scenario),
|
||||
weekStart,
|
||||
data_version: forecast.data_version,
|
||||
model_version: forecast.model_version,
|
||||
context_version: forecast.context_version,
|
||||
})
|
||||
build.response.why = planDrivers(build.response, mockContext, weekStart, scenario)
|
||||
return build.response
|
||||
}
|
||||
|
||||
const weekStart = planWeekStart(mockDemo.now)
|
||||
const build = buildStaffing({
|
||||
sensor,
|
||||
scenario,
|
||||
standard,
|
||||
points: applyScenario(forecast.points, scenario),
|
||||
weekStart,
|
||||
data_version: forecast.data_version,
|
||||
model_version: forecast.model_version,
|
||||
context_version: forecast.context_version,
|
||||
// The Go API owns the plan. The browser never computes staffing in this path.
|
||||
return apiRequest<StaffingResponse>('/api/staffing', {
|
||||
query: { sensor, scenario, standard },
|
||||
})
|
||||
build.response.why = planDrivers(build.response, mockContext, weekStart, scenario)
|
||||
return build.response
|
||||
})
|
||||
+46
-24
@@ -1,34 +1,56 @@
|
||||
import { apiForward, isMockMode } from '../utils/api'
|
||||
import { createMockTrainJob } from '../utils/train-jobs'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
let model: 'small' | 'forecast' = 'small'
|
||||
let filename: string | null = null
|
||||
if (isMockMode()) {
|
||||
let model: 'small' | 'forecast' = 'small'
|
||||
let filename: string | null = null
|
||||
|
||||
const contentType = getRequestHeader(event, 'content-type') ?? ''
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
const parts = await readMultipartFormData(event)
|
||||
for (const part of parts ?? []) {
|
||||
if (part.name === 'model' && part.data) {
|
||||
const value = part.data.toString()
|
||||
if (value === 'small' || value === 'forecast') model = value
|
||||
}
|
||||
if (part.name === 'file' && part.filename) {
|
||||
filename = part.filename
|
||||
const contentType = getRequestHeader(event, 'content-type') ?? ''
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
const parts = await readMultipartFormData(event)
|
||||
for (const part of parts ?? []) {
|
||||
if (part.name === 'model' && part.data) {
|
||||
const value = part.data.toString()
|
||||
if (value === 'small' || value === 'forecast') model = value
|
||||
}
|
||||
if (part.name === 'file' && part.filename) {
|
||||
filename = part.filename
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const body = await readBody<{ model?: 'small' | 'forecast'; path?: string }>(event).catch(() => null)
|
||||
if (body?.model === 'small' || body?.model === 'forecast') model = body.model
|
||||
if (body?.path) filename = body.path
|
||||
}
|
||||
|
||||
const job = createMockTrainJob(model, filename)
|
||||
setResponseStatus(event, 202)
|
||||
return {
|
||||
job_id: job.job_id,
|
||||
status: job.status,
|
||||
model: job.model,
|
||||
submitted_at: job.started_at,
|
||||
mock: true,
|
||||
}
|
||||
} else {
|
||||
const body = await readBody<{ model?: 'small' | 'forecast'; path?: string }>(event).catch(() => null)
|
||||
if (body?.model === 'small' || body?.model === 'forecast') model = body.model
|
||||
if (body?.path) filename = body.path
|
||||
}
|
||||
|
||||
const job = createMockTrainJob(model, filename)
|
||||
setResponseStatus(event, 202)
|
||||
return {
|
||||
job_id: job.job_id,
|
||||
status: job.status,
|
||||
model: job.model,
|
||||
submitted_at: job.started_at,
|
||||
mock: true,
|
||||
// Stream the multipart CSV to Go unchanged. The control credentials are
|
||||
// attached by the Nitro process and never reach the browser bundle.
|
||||
const contentType = getRequestHeader(event, 'content-type') ?? ''
|
||||
if (!contentType) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Content-Type must be application/json or multipart/form-data',
|
||||
})
|
||||
}
|
||||
|
||||
const body = await readRawBody(event)
|
||||
return apiForward(event, '/api/train', {
|
||||
method: 'POST',
|
||||
body,
|
||||
headers: { 'content-type': contentType },
|
||||
control: true,
|
||||
timeoutMs: 60_000,
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,19 @@
|
||||
import { apiRequest, isMockMode } from '../../utils/api'
|
||||
import { getMockTrainJob } from '../../utils/train-jobs'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
export default defineEventHandler(async (event) => {
|
||||
const jobId = getRouterParam(event, 'jobId')
|
||||
const job = jobId ? getMockTrainJob(jobId) : undefined
|
||||
if (!job) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown training job: ${jobId}` })
|
||||
if (!jobId) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'jobId is required' })
|
||||
}
|
||||
return job
|
||||
|
||||
if (isMockMode()) {
|
||||
const job = getMockTrainJob(jobId)
|
||||
if (!job) {
|
||||
throw createError({ statusCode: 404, statusMessage: `Unknown training job: ${jobId}` })
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
return apiRequest(`/api/train/${encodeURIComponent(jobId)}`, { control: true })
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
// Server-side Go API client. Every Nitro route uses this module so the browser
|
||||
// only ever talks to the Nuxt origin: the Go base URL and the control
|
||||
// credentials stay in the Node process.
|
||||
|
||||
interface ApiErrorEnvelope {
|
||||
error?: { code?: string; message?: string }
|
||||
message?: string
|
||||
statusMessage?: string
|
||||
}
|
||||
|
||||
export interface ApiRequestOptions {
|
||||
query?: Record<string, unknown>
|
||||
method?: 'GET' | 'POST'
|
||||
/** Raw request body, forwarded unchanged (multipart training uploads). */
|
||||
body?: any
|
||||
headers?: Record<string, string>
|
||||
/** 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(/\/+$/, '')
|
||||
}
|
||||
|
||||
/** True only when NUXT_USE_MOCK=1 / NUXT_PUBLIC_USE_MOCK=1 is set. */
|
||||
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 currently validates Basic auth; Bearer is accepted here for the future
|
||||
// token-based control surface without exposing the token to the browser.
|
||||
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<T>(path: string, options: ApiRequestOptions = {}): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: 'application/json', ...options.headers }
|
||||
if (options.control) {
|
||||
const authorization = controlAuthorization()
|
||||
if (authorization) headers.authorization = authorization
|
||||
}
|
||||
|
||||
const response = await $fetch
|
||||
.raw<T>(`${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 request body (training upload) and preserve Go's status code and
|
||||
* JSON body, including 202/400/409/502 responses that are part of the flow.
|
||||
*/
|
||||
export async function apiForward<T>(
|
||||
event: import('h3').H3Event,
|
||||
path: string,
|
||||
options: ApiRequestOptions = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: 'application/json', ...options.headers }
|
||||
if (options.control) {
|
||||
const authorization = controlAuthorization()
|
||||
if (authorization) headers.authorization = authorization
|
||||
}
|
||||
|
||||
const response = await $fetch
|
||||
.raw<T>(`${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<T extends string>(
|
||||
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
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import context from '../../mock/context.json'
|
||||
import demo from '../../mock/demo.json'
|
||||
import meta from '../../mock/meta.json'
|
||||
import scenario from '../../mock/scenario.json'
|
||||
import scenarios from '../../mock/scenarios.json'
|
||||
import sensors from '../../mock/sensors.json'
|
||||
|
||||
import forecast01 from '../../mock/forecast/hn-stadtgalerie-01.json'
|
||||
@@ -30,7 +29,6 @@ import type {
|
||||
ContextResponse,
|
||||
ForecastResponse,
|
||||
MetaResponse,
|
||||
ScenarioPreset,
|
||||
ScenarioState,
|
||||
Sensor,
|
||||
SeriesResponse,
|
||||
@@ -39,7 +37,6 @@ import type {
|
||||
export const mockMeta = meta as MetaResponse
|
||||
export const mockContext = context as ContextResponse
|
||||
export const mockSensors = sensors as Sensor[]
|
||||
export const mockScenarios = scenarios as ScenarioPreset[]
|
||||
export const mockScenario = scenario as ScenarioState
|
||||
export const mockDemo = demo as {
|
||||
now: string
|
||||
|
||||
Reference in new issue
Block a user