[API 통신 보완] $fetch방식으로 변경 및 로그인 처리 보완완

This commit is contained in:
2025-08-28 16:00:25 +09:00
parent ec6212c02f
commit 9eb6e23757
4 changed files with 76 additions and 62 deletions

View File

@@ -1,33 +1,45 @@
import { useFetch, useRuntimeConfig } from '#imports';
import { useRuntimeConfig } from "#imports";
import { useUserStore } from "~/stores/user";
export const useApi = <T>(
export const useApi = async <T>(
path: string,
options: {
method?: 'get' | 'post' | 'put' | 'delete'
body?: any
query?: Record<string, any>
headers?: HeadersInit
server?: boolean // ← 이 줄 추가!
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'
return useFetch<T>(() => `${config.public.apiBase}${config.public.contextPath}${path}`, {
method: method as any, // 타입 강제 우회
body: options.body,
query: options.query,
headers: {
Authorization: 'Bearer ' + userStore.getToken,
...options.headers,
},
onResponse({response}){
const accessToken = response.headers.get("Authorization") || "";
userStore.setToken(accessToken.replace("Bearer ", ""));
},
server: options.server // ← 이 줄 추가!
})
}
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;
}
};