Download fe/src/api/client.ts from valent-p/vibra: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/spaces/valent-p/vibra/resolve/main/fe/src/api/client.ts
- Command line
-
hf download hf://spaces/valent-p/vibra/fe/src/api/client.ts
-
curl -L -o client.ts https://huggingface.co/spaces/valent-p/vibra/resolve/main/fe/src/api/client.ts
1.93 kB
| const BASE_URL = import.meta.env.DEV ? 'http://localhost:8000' : ''; | |
| interface RequestOptions extends RequestInit { | |
| params?: Record<string, string>; | |
| } | |
| async function request<T>(path: string, options: RequestOptions = {}): Promise<T> { | |
| const token = localStorage.getItem('vibra_token'); | |
| // Setup headers | |
| const headers = new Headers(options.headers); | |
| if (token && !headers.has('Authorization')) { | |
| headers.set('Authorization', `Bearer ${token}`); | |
| } | |
| if (!headers.has('Content-Type') && !(options.body instanceof FormData)) { | |
| headers.set('Content-Type', 'application/json'); | |
| } | |
| // Setup Query parameters | |
| let url = `${BASE_URL}${path}`; | |
| if (options.params) { | |
| const searchParams = new URLSearchParams(options.params); | |
| url += `?${searchParams.toString()}`; | |
| } | |
| const response = await fetch(url, { | |
| ...options, | |
| headers, | |
| }); | |
| if (!response.ok) { | |
| let errorMessage = `Request failed: ${response.statusText}`; | |
| try { | |
| const errorData = await response.json(); | |
| errorMessage = errorData.detail || errorMessage; | |
| } catch { | |
| // JSON parsing failed, use fallback message | |
| } | |
| throw new Error(errorMessage); | |
| } | |
| // Return empty response if 204 No Content | |
| if (response.status === 204) { | |
| return {} as T; | |
| } | |
| return response.json(); | |
| } | |
| export const api = { | |
| get: <T>(path: string, options?: RequestOptions) => | |
| request<T>(path, { ...options, method: 'GET' }), | |
| post: <T>(path: string, body?: any, options?: RequestOptions) => | |
| request<T>(path, { | |
| ...options, | |
| method: 'POST', | |
| body: body instanceof FormData ? body : JSON.stringify(body) | |
| }), | |
| put: <T>(path: string, body?: any, options?: RequestOptions) => | |
| request<T>(path, { | |
| ...options, | |
| method: 'PUT', | |
| body: JSON.stringify(body) | |
| }), | |
| delete: <T>(path: string, options?: RequestOptions) => | |
| request<T>(path, { ...options, method: 'DELETE' }), | |
| }; | |