Download composables/useApi.ts from binhugg4/web: direct link, hf CLI and curl.
- Browser
- Download file 1.4 kB
-
https://huggingface.co/spaces/binhugg4/web/resolve/main/composables/useApi.ts
- Command line
-
hf download hf://spaces/binhugg4/web/composables/useApi.ts
-
curl -L -o useApi.ts https://huggingface.co/spaces/binhugg4/web/resolve/main/composables/useApi.ts
1.4 kB
| import type { ApiResponse } from "~/types/api" | |
| export function useApi() { | |
| const userStore = useUserStore() | |
| const config = useRuntimeConfig() | |
| function getHeaders(): Record<string, string> { | |
| const headers: Record<string, string> = {} | |
| if (userStore.token) { | |
| headers.Authorization = `Bearer ${userStore.token}` | |
| } | |
| return headers | |
| } | |
| async function unwrap<T>(raw: any): Promise<T> { | |
| if (raw && typeof raw === "object" && "code" in raw) { | |
| if (raw.code !== 0) { | |
| throw createError({ statusCode: raw.code, statusMessage: raw.msg || "Error" }) | |
| } | |
| return raw.data as T | |
| } | |
| return raw as T | |
| } | |
| async function get<T>(path: string, params?: Record<string, any>): Promise<T> { | |
| const raw = await $fetch<any>(`${config.public.apiBase}${path}`, { | |
| method: "GET", | |
| params, | |
| headers: getHeaders(), | |
| }) | |
| return unwrap<T>(raw) | |
| } | |
| async function post<T>(path: string, body?: Record<string, any>): Promise<T> { | |
| const raw = await $fetch<any>(`${config.public.apiBase}${path}`, { | |
| method: "POST", | |
| body, | |
| headers: getHeaders(), | |
| }) | |
| return unwrap<T>(raw) | |
| } | |
| async function del<T>(path: string): Promise<T> { | |
| const raw = await $fetch<any>(`${config.public.apiBase}${path}`, { | |
| method: "DELETE", | |
| headers: getHeaders(), | |
| }) | |
| return unwrap<T>(raw) | |
| } | |
| return { get, post, del } | |
| } |