40 lines
1.4 KiB
TypeScript
40 lines
1.4 KiB
TypeScript
/// <reference types="vite/client" />
|
|
const API_URL = import.meta.env.VITE_EFC_API_URL || 'http://localhost:8000';
|
|
import { fetchWithAuth, postWithAuth, putWithAuth, deleteWithAuth } from '../fetchWithAuth';
|
|
import { extractApiError } from './apiError';
|
|
|
|
async function handleResponse(response: Response) {
|
|
if (response.status === 401) throw new Error('SESSION_EXPIRED');
|
|
if (!response.ok) throw new Error(await extractApiError(response));
|
|
const contentType = response.headers.get('content-type');
|
|
if (!contentType?.includes('application/json')) return null;
|
|
return response.json();
|
|
}
|
|
|
|
export async function fetchUsers() {
|
|
const res = await fetchWithAuth(`${API_URL}/user/users/`);
|
|
return handleResponse(res);
|
|
}
|
|
|
|
export async function createUser(userData: object) {
|
|
const res = await postWithAuth(`${API_URL}/user/users/`, userData);
|
|
return handleResponse(res);
|
|
}
|
|
|
|
export async function updateUser(id: string | number, userData: object) {
|
|
const res = await putWithAuth(`${API_URL}/user/users/${id}/`, userData);
|
|
return handleResponse(res);
|
|
}
|
|
|
|
export async function deleteUser(id: string | number) {
|
|
const res = await deleteWithAuth(`${API_URL}/user/users/${id}/`);
|
|
if (res.status === 401) throw new Error('SESSION_EXPIRED');
|
|
if (!res.ok) throw new Error(await extractApiError(res));
|
|
return true;
|
|
}
|
|
|
|
export async function getCurrentUser() {
|
|
const res = await fetchWithAuth(`${API_URL}/user/users/me/`);
|
|
return handleResponse(res);
|
|
}
|