Replies: 2 comments
-
@dongkyun-dev @wonjin-dev // apis/core.ts
import { HTTP_STATUS_CODE } from '@constants/http';
import { isExpiredAccessToken, isNotExistAuthHeader, isNotRegisteredMember } from '@lib/util/http';
import { storage } from '@lib/util/storage';
import axios, { type AxiosResponse } from 'axios';
import { authApi } from './auth';
export const HTTP_BASE_URL = process.env.NODE_ENV === 'production' ? '' : '';
const options = {
headers: {
'Content-Type': 'application/json',
},
};
const instance = axios.create({
baseURL: HTTP_BASE_URL,
...options,
});
instance.interceptors.response.use(
(response: AxiosResponse) => {
const token = storage.getAccessToken();
if (token) {
setAccessToken(token);
}
return response.data.data;
},
async error => {
const {
config: originalRequest,
response: {
status,
data: { message },
},
} = error;
if (originalRequest && status === HTTP_STATUS_CODE.UNAUTHORIZED) {
if (isNotRegisteredMember(message)) {
/**
* [status:401] 등록된 기존 회원이 아닌 경우
*/
return Promise.reject(error);
}
if (isNotExistAuthHeader(message)) {
/**
* [status:401] 헤더에 token이 없는 경우
*/
const accessToken = storage.getAccessToken();
if (accessToken) {
setAccessToken(accessToken);
} else {
const { id_token, refresh_token } = await authApi.silentRefresh();
setAccessToken(id_token);
storage.setAccessToken(id_token);
if (isExpiredAccessToken(refresh_token)) {
storage.setRefreshToken(refresh_token);
}
}
return instance(originalRequest);
}
}
return Promise.reject(error);
},
);
export const setAccessToken = (token: string) => {
instance.defaults.headers.common.Authorization = `Bearer ${token}`;
};
export const removeAccessToken = () => {
instance.defaults.headers.common.Authorization = '';
};
export default instance; // apis/members.ts
import type { MemberInfoParams, MemberResponse } from '@/_types/response/member';
import instance from './core';
const MEMBER_API_URL = '/api/member';
export const memberApi = {
/**
* @description 회원정보 조회
*/
getMember: () => instance.get<unknown, MemberResponse>(MEMBER_API_URL),
/**
* @description 회원정보 등록
*/
postMember: (info: MemberInfoParams) =>
instance.post<MemberInfoParams, MemberResponse>(MEMBER_API_URL, info),
/**
* @description 회원정보 삭제
*/
deleteMember: () => instance.delete(MEMBER_API_URL),
/**
* @description 회원정보 수정
*/
patchMember: (info: MemberInfoParams) =>
instance.patch<MemberInfoParams, MemberResponse>(MEMBER_API_URL, info),
}; 저는 이렇게 작성했던 것 같습니다~! |
Beta Was this translation helpful? Give feedback.
0 replies
-
enum Method {
get = 'get',
post = 'post',
patch = 'patch',
delete = 'delete',
put = 'put'
}
interface Response<T> {
data: T;
headers: Headers;
status: number;
}
type ApiFn<T> = (
url: string,
params?: Params,
config?: AxiosRequestConfig
) => Promise<Response<T>>;
const requestHeader = new AxiosHeaders({
'content-type': 'application/json'
});
const controller = new AbortController();
const instance = axios.create({
baseURL: 'server-domain',
headers: requestHeader,
signal: controller.signal
});
instance.interceptors.request.use(
(config) => {},
(error) => {}
);
instance.interceptors.response.use(
(response: AxiosResponse): AxiosResponse => {},
(error: AxiosError): Promise<AxiosError> => {}
);
const apiGet =
<T>(): ApiFn<T> =>
(url, data, config) =>
instance.get(url, { ...config, params: data });
const apiPost =
<T>(): ApiFn<T> =>
(url, data, config) =>
instance.post(url, data, config);
const apiPut =
<T>(): ApiFn<T> =>
(url, data, config) =>
instance.put(url, data, config);
const apiPatch =
<T>(): ApiFn<T> =>
(url, data, config) =>
instance.patch(url, data, config);
const apiDelete =
<T>(): ApiFn<T> =>
(url, config) =>
instance.delete(url, config);
const requests = <T>(method: Method): ApiFn<T> =>
({
[Method.get]: apiGet<T>(),
[Method.put]: apiPut<T>(),
[Method.post]: apiPost<T>(),
[Method.patch]: apiPatch<T>(),
[Method.delete]: apiDelete<T>()
}[method]);
export const api = async <T>(
method: MethodType,
url: string,
params?: Params,
config?: AxiosRequestConfig
): Promise<Response<T>> => {
const { data, headers, status } = await requests<T>(Method[method])(
url,
params,
config
);
return { data, headers, status };
}; 거의 동일한 형태인데 이런식의 형태로 사용하고 있습니다. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
#24 [Feature/BAR-172] API 레이어 구현
Beta Was this translation helpful? Give feedback.
All reactions