twin-optimiser/frontend/src/api.ts
jtricerolph 7c8991d5ce Redirect to login on mid-session 401 instead of silently failing
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-12 20:09:17 +00:00

40 lines
1.3 KiB
TypeScript

import type { GridData, AppSettings } from './types'
const BASE = '/twin-optimiser/api'
async function request<T>(path: string, opts?: RequestInit): Promise<T> {
const res = await fetch(BASE + path, { credentials: 'include', ...opts })
if (res.status === 401) {
;(window.top ?? window).location.href = '/login'
throw new Error('Unauthenticated')
}
if (!res.ok) {
const body = await res.json().catch(() => ({})) as { error?: string }
throw new Error(body.error || `HTTP ${res.status}`)
}
return res.json() as Promise<T>
}
export function getGrid(startDate?: string, days = 14, force = false): Promise<GridData> {
const p = new URLSearchParams()
if (startDate) p.set('start_date', startDate)
p.set('days', String(days))
if (force) p.set('force', '1')
return request<GridData>(`/grid?${p}`)
}
export function getSettings(): Promise<AppSettings> {
return request<AppSettings>('/settings')
}
export function postSettings(settings: Partial<AppSettings>): Promise<AppSettings> {
return request<AppSettings>('/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings),
})
}
export function testNewbook(): Promise<{ ok: boolean; message?: string; error?: string }> {
return request('/newbook/test', { method: 'POST' })
}