Files
NetMapper2026/frontend/src/lib/api.ts
T

65 lines
2.4 KiB
TypeScript
Raw Normal View History

import { getToken, clearSession } from './session';
import type { NetObject, ServiceInfo } from '../types';
const BACKEND = '/backend';
const AGENT = '/api';
export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
const token = getToken();
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(init.headers as Record<string, string> ?? {}),
};
if (token) headers['Authorization'] = `Bearer ${token}`;
const res = await fetch(`${BACKEND}${path}`, { ...init, headers });
if (res.status === 401) { clearSession(); window.location.reload(); }
return res;
}
export async function apiGet<T>(path: string): Promise<T> {
const res = await apiFetch(path);
if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`);
return res.json();
}
export async function apiPost<T>(path: string, body?: unknown): Promise<T> {
const res = await apiFetch(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined });
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.detail ?? `POST ${path} failed: ${res.status}`);
}
return res.json();
}
export async function apiPatch<T>(path: string, body?: unknown): Promise<T> {
const res = await apiFetch(path, { method: 'PATCH', body: body ? JSON.stringify(body) : undefined });
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.detail ?? `PATCH ${path} failed: ${res.status}`);
}
return res.json();
}
export async function apiDelete(path: string): Promise<void> {
const res = await apiFetch(path, { method: 'DELETE' });
if (!res.ok) throw new Error(`DELETE ${path} failed: ${res.status}`);
}
// Inventory objects - authenticated via apiGet
export async function fetchObjects(): Promise<NetObject[]> {
return apiGet<NetObject[]>('/objects');
}
// Legacy agent calls (unauthenticated local agent)
export async function fetchServices(): Promise<ServiceInfo[]> {
const res = await fetch(`${AGENT}/services`);
if (!res.ok) throw new Error('Impossibile leggere lo stato dei servizi');
return res.json();
}
export async function serviceAction(name: string, action: 'start' | 'stop' | 'restart') {
const res = await fetch(`${AGENT}/services/${encodeURIComponent(name)}/${action}`, { method: 'POST' });
if (!res.ok) throw new Error(`Azione ${action} fallita su ${name}`);
return res.json();
}