/** * @license * SPDX-License-Identifier: Apache-2.0 */ class ApiClient { private getHeaders() { const headers: Record = { 'Content-Type': 'application/json', 'Accept': 'application/json', }; if (typeof window !== 'undefined') { const token = localStorage.getItem('stateless_ops_token'); if (token) { headers['Authorization'] = `Bearer ${token}`; } } return headers; } async request(path: string, options: RequestInit = {}): Promise { const url = path; const headers = { ...this.getHeaders(), ...options.headers }; // FormData 전송 시 Content-Type 헤더가 없어야 브라우저가 boundary를 자동으로 지정합니다. if (options.body instanceof FormData) { delete headers['Content-Type']; } const response = await fetch(url, { ...options, headers }); if (response.status === 401) { if (typeof window !== 'undefined') { localStorage.removeItem('stateless_ops_token'); localStorage.removeItem('stateless_ops_user_id'); window.location.href = '/ops/login'; } throw new Error('인증이 만료되었습니다. 다시 로그인해주세요.'); } if (!response.ok) { const errData = await response.json().catch(() => ({ detail: '알 수 없는 서버 오류' })); throw new Error(errData.detail || 'API 요청 실패'); } if (response.status === 204) { return {} as T; } return response.json() as Promise; } get(path: string, options?: RequestInit): Promise { return this.request(path, { ...options, method: 'GET' }); } post(path: string, body?: any, options?: RequestInit): Promise { const isFormData = body instanceof FormData; return this.request(path, { ...options, method: 'POST', body: isFormData ? body : (body ? JSON.stringify(body) : undefined), }); } put(path: string, body?: any, options?: RequestInit): Promise { return this.request(path, { ...options, method: 'PUT', body: body ? JSON.stringify(body) : undefined, }); } patch(path: string, body?: any, options?: RequestInit): Promise { return this.request(path, { ...options, method: 'PATCH', body: body ? JSON.stringify(body) : undefined, }); } delete(path: string, options?: RequestInit): Promise { return this.request(path, { ...options, method: 'DELETE' }); } } export const apiClient = new ApiClient();