60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
const API_BASE_URL = import.meta.env.NSCT_API_BASE_URL || 'http://localhost:8080';
|
|
|
|
interface ApiConfig {
|
|
apiKey?: string;
|
|
}
|
|
|
|
function headers(config?: ApiConfig): Record<string, string> {
|
|
const h: Record<string, string> = {
|
|
'Content-Type': 'application/json'
|
|
};
|
|
if (config?.apiKey) {
|
|
h['X-API-Key'] = config.apiKey;
|
|
}
|
|
return h;
|
|
}
|
|
|
|
export async function apiPost<T>(
|
|
path: string,
|
|
body?: unknown,
|
|
config?: ApiConfig
|
|
): Promise<T> {
|
|
const res = await fetch(`${API_BASE_URL}${path}`, {
|
|
method: 'POST',
|
|
headers: headers(config),
|
|
body: body ? JSON.stringify(body) : undefined
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`API Error ${res.status}: ${res.statusText}`);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
export async function apiGet<T>(
|
|
path: string,
|
|
config?: ApiConfig
|
|
): Promise<T> {
|
|
const res = await fetch(`${API_BASE_URL}${path}`, {
|
|
headers: headers(config)
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`API Error ${res.status}: ${res.statusText}`);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
export async function apiDelete<T>(
|
|
path: string,
|
|
config?: ApiConfig
|
|
): Promise<T> {
|
|
const res = await fetch(`${API_BASE_URL}${path}`, {
|
|
method: 'DELETE',
|
|
headers: headers(config)
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`API Error ${res.status}: ${res.statusText}`);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
export { API_BASE_URL }; |