[API 개선] useApi 함수 리팩토링 및 API 플러그인 추가로 API 호출 방식 통일

This commit is contained in:
2025-08-29 10:32:21 +09:00
parent 41f8ec3232
commit 8af0cf5a44
2 changed files with 79 additions and 35 deletions

View File

@@ -1,36 +1,36 @@
import { useRuntimeConfig } from "#imports";
export const useApi = async <T>(
path: string,
options: {
method?: "get" | "post" | "put" | "delete";
body?: any;
query?: Record<string, any>;
headers?: HeadersInit;
credentials?: RequestCredentials;
} = {}
): Promise<T> => {
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,
credentials: options.credentials || "include", // 쿠키 자동 전송
headers: {
"Content-Type": "application/json",
...options.headers,
},
}
);
return response;
} catch (error) {
console.error("API 호출 실패:", error);
throw error;
}
/**
* API 호출을 위한 편의 함수
*
* @template T - 응답 데이터의 타입
* @param path - API 엔드포인트 경로 (예: '/users', '/users/1')
* @param opts - 요청 옵션 (method, body, headers 등)
* @returns Promise<T> - API 응답 데이터
*
* @example
* // GET 요청
* const users = await useApi<User[]>('/users')
*
* // POST 요청
* const newUser = await useApi<User>('/users', {
* method: 'POST',
* body: { name: 'John', email: 'john@example.com' }
* })
*
* // PUT 요청
* const updatedUser = await useApi<User>('/users/1', {
* method: 'PUT',
* body: { name: 'John Updated' }
* })
*
* // DELETE 요청
* await useApi('/users/1', { method: 'DELETE' })
*
* // FormData 업로드
* const formData = new FormData()
* formData.append('file', file)
* await useApi('/upload', { method: 'POST', body: formData })
*/
export const useApi = <T>(path: string, opts?: any): Promise<T> => {
const { $api } = useNuxtApp();
return ($api as any)(path, opts);
};