web / composables /useApi.ts
hanbinsite's picture
feat: implement all web pages with player, search, favorites, auth, useApi composable
dfa6264
Raw History Blame Contribute Delete
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 }
}