Init first files
This commit is contained in:
28
frontend/src/api.js
Normal file
28
frontend/src/api.js
Normal file
@@ -0,0 +1,28 @@
|
||||
const API_URL = import.meta.env.VITE_API_URL || "http://localhost:8000/api/v1";
|
||||
|
||||
export async function apiFetch(path, options = {}, tokens, onUnauthorized) {
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
...(options.headers || {}),
|
||||
};
|
||||
if (tokens?.accessToken) {
|
||||
headers.Authorization = `Bearer ${tokens.accessToken}`;
|
||||
}
|
||||
|
||||
let res = await fetch(`${API_URL}${path}`, { ...options, headers });
|
||||
if (res.status === 401 && tokens?.refreshToken && onUnauthorized) {
|
||||
const refreshed = await onUnauthorized();
|
||||
if (refreshed) {
|
||||
headers.Authorization = `Bearer ${refreshed.accessToken}`;
|
||||
res = await fetch(`${API_URL}${path}`, { ...options, headers });
|
||||
}
|
||||
}
|
||||
if (!res.ok) {
|
||||
const txt = await res.text();
|
||||
throw new Error(txt || `HTTP ${res.status}`);
|
||||
}
|
||||
if (res.status === 204) return null;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export { API_URL };
|
||||
Reference in New Issue
Block a user