Files
creator2/frontend/src/api.js
2026-07-10 17:56:41 +02:00

56 lines
2.4 KiB
JavaScript

const BASE = import.meta.env.DEV ? 'http://localhost:8000' : ''
async function req(pfad, opts = {}) {
const res = await fetch(BASE + pfad, {
headers: { 'Content-Type': 'application/json' },
...opts,
})
if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`)
return res.json()
}
export const api = {
topics: () => req('/api/topics'),
topicAnlegen: (daten) => req('/api/topics', { method: 'POST', body: JSON.stringify(daten) }),
start: (topic, budget) =>
req(`/api/topics/${topic}/start`, { method: 'POST', body: JSON.stringify({ budget }) }),
stop: (topic) => req(`/api/topics/${topic}/stop`, { method: 'POST', body: '{}' }),
sollReset: (topic) => req(`/api/topics/${topic}/soll-reset`, { method: 'POST', body: '{}' }),
vollReset: (topic) => req(`/api/topics/${topic}/voll-reset`, { method: 'POST', body: '{}' }),
setAuto: (topic, ebene, an) =>
req(`/api/topics/${topic}/auto`, { method: 'PATCH', body: JSON.stringify({ ebene, an }) }),
ebeneEntfernen: (topic, ebene) =>
req(`/api/topics/${topic}/ebene/${ebene}/entfernen`, { method: 'POST', body: '{}' }),
topicLoeschen: (topic) => req(`/api/topics/${topic}`, { method: 'DELETE' }),
state: (topic) => req(`/api/topics/${topic}/state`),
guide: (topic) => req(`/api/topics/${topic}/guide`),
ueben: (topic) => req(`/api/topics/${topic}/ueben`),
antwort: (artefakt_id, richtig) =>
req('/api/ueben/antwort', { method: 'POST', body: JSON.stringify({ artefakt_id, richtig }) }),
kennzahlen: (runId) => req(`/api/runs/${runId}/kennzahlen`),
transferInfo: () => req('/api/transfer'),
transfer: (topic, richtung) =>
req(`/api/topics/${topic}/transfer/${richtung}`, { method: 'POST', body: '{}' }),
}
export function wsVerbinden(onEvent) {
// Protokoll an die Seite koppeln: HTTPS erlaubt nur wss:// (Mixed Content)
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws'
const url = (import.meta.env.DEV ? 'ws://localhost:8000' : `${wsProto}://${location.host}`) + '/ws'
let ws
const verbinden = () => {
try {
ws = new WebSocket(url)
} catch (e) {
// nie den Aufrufer mitreißen (der SecurityError killte sonst den Poll)
console.error('WebSocket nicht verfügbar:', e)
return
}
ws.onopen = () => onEvent({ typ: 'verbunden' }) // nach Reconnect: Stand neu laden
ws.onmessage = (e) => onEvent(JSON.parse(e.data))
ws.onclose = () => setTimeout(verbinden, 2000)
}
verbinden()
return () => ws && ws.close()
}