[API 개선] useApi 함수에 에러 처리 옵션 추가 및 사용 예시 업데이트

This commit is contained in:
2025-09-03 17:17:53 +09:00
parent 8af0cf5a44
commit 5f1d1f5018
2 changed files with 115 additions and 17 deletions

View File

@@ -3,11 +3,11 @@
*
* @template T - 응답 데이터의 타입
* @param path - API 엔드포인트 경로 (예: '/users', '/users/1')
* @param opts - 요청 옵션 (method, body, headers 등)
* @param options - 요청 및 에러 처리 옵션
* @returns Promise<T> - API 응답 데이터
*
* @example
* // GET 요청
* // GET 요청 (기본)
* const users = await useApi<User[]>('/users')
*
* // POST 요청
@@ -16,21 +16,75 @@
* body: { name: 'John', email: 'john@example.com' }
* })
*
* // PUT 요청
* const updatedUser = await useApi<User>('/users/1', {
* method: 'PUT',
* body: { name: 'John Updated' }
* })
* // 에러 시 alert 표시
* const data = await useApi<User[]>('/users', { showAlert: true })
*
* // DELETE 요청
* await useApi('/users/1', { method: 'DELETE' })
* // 에러를 직접 처리
* try {
* const data = await useApi<User[]>('/users', { handleError: false })
* } catch (error) {
* // 직접 에러 처리
* }
*
* // 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> => {
export const useApi = async <T>(
path: string,
options?: {
// API 요청 옵션
method?: string;
body?: any;
headers?: Record<string, string>;
// 에러 처리 옵션
handleError?: boolean; // true: 에러를 null로 반환, false: 에러를 다시 던짐
showAlert?: boolean; // true: 에러 시 alert 표시
}
): Promise<T> => {
const { $api } = useNuxtApp();
return ($api as any)(path, opts);
// 기본값 설정
const {
method = "GET",
body,
headers,
handleError = true,
showAlert = true,
} = options || {};
// API 요청 옵션 구성
const apiOpts = {
method,
...(body && { body }),
...(headers && { headers }),
};
return ($api as any)(path, apiOpts).catch((error: any) => {
// 사용자에게 알림 표시
if (showAlert) {
const status = error.response?.status;
let message =
status === 404
? "요청한 리소스를 찾을 수 없습니다."
: status === 500
? "서버 오류가 발생했습니다."
: "요청 처리 중 오류가 발생했습니다.";
// 서버에서 온 에러 메시지가 있으면 우선 사용
if (error.response?._data?.description) {
message = error.response._data.description;
}
alert(message);
}
// 에러 처리 방식에 따라 반환
if (handleError) {
return null as T; // 에러를 null로 반환
} else {
throw error; // 에러를 다시 던짐
}
});
};