Files
2026-06-04 11:44:20 +02:00

107 lines
3.0 KiB
TypeScript

import type {
ChartConfig,
AlertConfig,
TriggeredAlert,
SignalRow,
SessionBoundary,
UpsRow,
TimeMode,
} from './types';
let _token = '';
export function setToken(token: string) {
_token = token;
}
function url(
path: string,
params: Record<string, string | string[] | boolean | number | undefined> = {},
) {
const u = new URL(
path,
typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000',
);
u.searchParams.set('token', _token);
for (const [k, v] of Object.entries(params)) {
if (v === undefined) continue;
if (Array.isArray(v)) v.forEach((val) => u.searchParams.append(k, String(val)));
else u.searchParams.set(k, String(v));
}
return u.toString();
}
async function get<T>(
path: string,
params?: Record<string, string | string[] | boolean | number | undefined>,
): Promise<T> {
const res = await fetch(url(path, params));
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
async function mutate<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(url(path), {
method,
headers: { 'Content-Type': 'application/json' },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
export function fetchSignals(params: {
combinator?: string[];
item?: string[];
exclude?: string[];
signal?: string;
time_mode?: TimeMode;
from?: string;
to?: string;
regex?: boolean;
order_by?: string;
limit?: number;
}): Promise<SignalRow[]> {
return get('/api/signals', params as Record<string, string | string[]>);
}
export function fetchUps(params: {
combinator?: string;
from?: string;
to?: string;
}): Promise<UpsRow[]> {
return get('/api/ups', params);
}
export function fetchSessions(from: string, to: string): Promise<SessionBoundary[]> {
return get('/api/sessions', { from, to });
}
export function fetchCharts(): Promise<ChartConfig[]> {
return get('/api/charts');
}
export function createChart(body: Omit<ChartConfig, 'id'>): Promise<ChartConfig> {
return mutate('POST', '/api/charts', body);
}
export function updateChart(id: string, body: Partial<ChartConfig>): Promise<ChartConfig> {
return mutate('PUT', `/api/charts/${id}`, body);
}
export function deleteChart(id: string): Promise<{ ok: boolean }> {
return mutate('DELETE', `/api/charts/${id}`);
}
export function fetchAlerts(): Promise<AlertConfig[]> {
return get('/api/alerts');
}
export function createAlert(body: Omit<AlertConfig, 'id' | 'active'>): Promise<AlertConfig> {
return mutate('POST', '/api/alerts', body);
}
export function updateAlert(id: string, body: Partial<AlertConfig>): Promise<AlertConfig> {
return mutate('PUT', `/api/alerts/${id}`, body);
}
export function deleteAlert(id: string): Promise<{ ok: boolean }> {
return mutate('DELETE', `/api/alerts/${id}`);
}
export function checkAlerts(): Promise<TriggeredAlert[]> {
return get('/api/alerts/check');
}