Files
bio_frontend/composables/useApi.ts

46 lines
1.2 KiB
TypeScript

import { useRuntimeConfig } from "#imports";
import { useUserStore } from "~/stores/user";
export const useApi = async <T>(
path: string,
options: {
method?: "get" | "post" | "put" | "delete";
body?: any;
query?: Record<string, any>;
headers?: HeadersInit;
} = {}
): Promise<T> => {
const userStore = useUserStore();
const config = useRuntimeConfig();
const method = options.method ? options.method.toUpperCase() : "GET";
try {
const response = await $fetch<T>(
`${config.public.apiBase}${config.public.contextPath}${path}`,
{
method: method as any,
body: options.body,
query: options.query,
headers: {
Authorization: "Bearer " + userStore.token,
...options.headers,
},
onResponse({ response }) {
const authHeader = response.headers.get("Authorization");
if (authHeader && authHeader.startsWith("Bearer ")) {
const accessToken = authHeader.substring(7);
userStore.setToken(accessToken);
}
},
}
);
return response;
} catch (error) {
console.error("API 호출 실패:", error);
throw error;
}
};