Files
web-nuxt/server/api/playground.get.ts
T
2026-11-14 21:04:23 +01:00

68 lines
2.3 KiB
TypeScript

import { HORIZONS, SCENARIOS } from '../../shared/types'
import type {
Horizon,
PlaygroundForecastResponse,
Scenario,
} from '../../shared/types'
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
function numberParam(
value: unknown,
name: string,
min: number,
max: number,
): number | undefined {
if (value === undefined || value === '') return undefined
const raw = Array.isArray(value) ? value[0] : value
const parsed = Number(raw)
if (!Number.isFinite(parsed)) {
throw createError({ statusCode: 400, statusMessage: `${name} must be a number` })
}
if (parsed < min || parsed > max) {
throw createError({
statusCode: 400,
statusMessage: `${name} must be between ${min} and ${max}`,
})
}
return parsed
}
function booleanParam(value: unknown, name: string): boolean | undefined {
if (value === undefined || value === '') return undefined
const raw = String(Array.isArray(value) ? value[0] : value).toLowerCase()
if (raw === 'true' || raw === '1') return true
if (raw === 'false' || raw === '0') return false
throw createError({ statusCode: 400, statusMessage: `${name} must be a boolean` })
}
// Browser-facing playground proxy. The page calls /api/playground; only this
// Nitro route talks to the public Go endpoint.
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const sensor = sensorParam(query.sensor)
const horizon = enumParam<Horizon>(query.horizon, HORIZONS, 'horizon', '48h')
const scenario = enumParam<Scenario>(query.scenario, SCENARIOS, 'scenario', 'base')
const tempC = numberParam(query.temp_c, 'temp_c', -30, 50)
const precipMm = numberParam(query.precip_mm, 'precip_mm', 0, 50)
const isHoliday = booleanParam(query.is_holiday, 'is_holiday')
if (isMockMode()) {
throw createError({
statusCode: 503,
statusMessage:
'Mock mode is enabled, but the playground has no demo forecast. Start the real Python and Go services or unset NUXT_PUBLIC_USE_MOCK.',
})
}
return apiRequest<PlaygroundForecastResponse>('/api/playground/forecast', {
query: {
sensor,
horizon,
scenario,
...(tempC === undefined ? {} : { temp_c: tempC }),
...(precipMm === undefined ? {} : { precip_mm: precipMm }),
...(isHoliday === undefined ? {} : { is_holiday: isHoliday }),
},
})
})