org-network / frontend /src /services /apiClient.ts
5minbetter's picture
deploy: initial clean workspace without lfs history
33d9e63
Raw
History Blame Contribute Delete
2.56 kB
/**
* @license
* SPDX-License-Identifier: Apache-2.0
*/
class ApiClient {
private getHeaders() {
const headers: Record<string, string> = {
'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<T>(path: string, options: RequestInit = {}): Promise<T> {
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<T>;
}
get<T>(path: string, options?: RequestInit): Promise<T> {
return this.request<T>(path, { ...options, method: 'GET' });
}
post<T>(path: string, body?: any, options?: RequestInit): Promise<T> {
const isFormData = body instanceof FormData;
return this.request<T>(path, {
...options,
method: 'POST',
body: isFormData ? body : (body ? JSON.stringify(body) : undefined),
});
}
put<T>(path: string, body?: any, options?: RequestInit): Promise<T> {
return this.request<T>(path, {
...options,
method: 'PUT',
body: body ? JSON.stringify(body) : undefined,
});
}
patch<T>(path: string, body?: any, options?: RequestInit): Promise<T> {
return this.request<T>(path, {
...options,
method: 'PATCH',
body: body ? JSON.stringify(body) : undefined,
});
}
delete<T>(path: string, options?: RequestInit): Promise<T> {
return this.request<T>(path, { ...options, method: 'DELETE' });
}
}
export const apiClient = new ApiClient();