README
RESTful Libs
Wrapped library for RESTful API processing module
This project has been created by Vessel CLI. For a simple and quick reference about it, click here.
About
Cancellable Axios, AxiosRetry 등의 모듈을 이용하여 RESTful API 요청에 대한 일괄적인 프로세스를 수행. SPA 및 SSR 프로젝트에서 사용 가능하다.
Installation
해당 모듈을 사용할 프로젝트에서는 아래와 같이 설치한다.
$ npm install --save @mornya/restful-libs
or
$ yarn add @mornya/restful-libs
Usage
최초 랜더링 되는 앱에 아래와 같이 axiosDefaultConfig
메소드를 이용하여 설정 부분을 추가해주면 된다.
example Vue.js
<script>
import { axiosDefaultConfig } from '@mornya/restful-libs';
export default {
created () {
axiosDefaultConfig({
defaults: {
baseURL: '/test',
method: 'get',
timeout: 3000,
},
isThrowsOnError: true,
onInvalidate (which, error) {
console.log('is error on request or response?', which)
console.error(error.message)
},
});
},
};
</script>
example React.js
import React, { useEffect } from 'react';
import { axiosDefaultConfig } from '@mornya/restful-libs';
type Props = {};
const ApplicationProvider: React.FC<Props> = (props: Props) => {
useEffect(() => {
axiosDefaultConfig({
defaults: {
baseURL: '/test',
method: 'get',
timeout: 3000,
},
isThrowsOnError: true,
onInvalidate (which, error) {
console.log('is error on request or response?', which)
console.error(error.message)
},
});
}, []); // mounted
return (<></>);
};
export default ApplicationProvider;
Provides Axios Static library
axios
라이브러리가 직접적으로 필요하다면 아래와 같이 import하여 사용한다.
import { axios } from '@mornya/restful-libs';
Configuration
axiosDefaultConfig
메소드는 이미 오버라이드 된 axios 기본 설정을 사용자에 맞게 오버라이드 시켜줄 수 있다. interface 선언과 아래 샘플을 참고하면 된다.
import { axiosDefaultConfig, AxiosRequestConfig } from '@mornya/restful-libs';
const axiosConfig: AxiosRequestConfig = {
// ===== axios default request 설정 =====
defaults: {
method: 'GET',
baseURL: '',
headers: {
common: {},
get: { 'Content-Type': 'application/json;charset=UTF-8' },
head: { 'Content-Type': 'application/json;charset=UTF-8' },
patch: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
post: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
put: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
delete: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
},
withCredentials: true,
timeout: 5000,
},
// ===== restful 라이브러리 설정 =====
isShowLog: true, // 로그 출력 여부
isLogFullResponse: false, // response 로그에 전체 항목 표시 여부
isThrowsOnError: true, // response 오류 발생시 throw 할 것인지 여부
isCancelDuplicateRequests: true, // 동일 request를 중복으로 호출시 취소 여부
requestsThreshold: 100, // 최대 동시 호출 request 갯수 제한
'axios-retry': {
// 요청 실패 혹은 오류시 재시도를 위한 axios-retry 모듈에 대한 옵션
// 관련 내용은 https://github.com/softonic/axios-retry 참고
retries: 3, // 재시도 횟수
...
},
// request config에서 "baseURL" 및 "url"의 key에 해당되는 value값으로 치환한다.
// (로컬 서버에서 프록시 사용시 코드상의 url을 배포 단계별로 조작하지 않아도 되게 하기 위함)
resolveRequestURL: process.env.NODE_ENV !== 'production'
? undefined // development 환경에서는 프록시 서버를 통하도록 미사용처리
: {
'/api-service': 'https://service-api.my-domain.com',
},
onRequest (config, currReqs) {
console.log(config, currReqs);
// 만약 config 변경이 있다면 리턴하여 반영, 그렇지 않으면 리턴 불필요.
// return config;
},
onResponse (response, currReqs) {
console.log(response, currReqs);
// onRequest와 마찬가지로 response 변경시 리턴.
// return response;
},
onRequestError (error, currReqs) { console.log(error, currReqs); },
onResponseError (error, currReqs) { console.log(error, currReqs); },
onInvalidate (which, error) {
// response 오류처리만 이곳에서 한다.
// request 정보는 error.request에서, response 정보는 error.response에서 확인 가능.
if (which === 'request') {
console.error(`Request error: ${error}`);
} else {
console.error(`Response error: ${error}`);
}
},
};
axiosDefaultConfig(axiosConfig);
Modules in the package
본 패키지에는 아래와 같은 모듈들을 포함한다.
제공되는 모듈과 메소드 사용법 등은 코드 스니핏을 참고한다.
AxiosLib module
기본 모듈이며, 다음과 같은 메소드들을 제공한다.
axiosDefaultConfig
axios 라이브러리 설정 및 restful 라이브러리 설정으로 초기화 한다.
위의 Configuration 항목 참조
restApi
axios 라이브러리로 요청을 수행한다.
Request 설정 중
ignoreCancel
값은 일괄적인 요청취소에 대해 무시하도록 설정한다.
import { restApi, AxiosResponse } from '@mornya/restful-libs';
restApi({
headers: {
// headers for POST method
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
method: 'POST',
url: '/mock/test',
data: { test: 'test' },
ignoreCancel: true,
})
.then((response: AxiosResponse) => console.log(response))
.catch((reason: any) => console.error(reason));
restApis
axios 라이브러리로 여러 요청을 병렬로 수행한다.
import { restApis, AxiosResponse } from '@mornya/restful-libs';
restApis([
{
method: 'POST',
url: '/mock/test1',
data: { test: 'test1' },
},
{
method: 'POST',
url: '/mock/test2',
data: { test: 'test2' },
},
])
.then(([response1, response2]: AxiosResponse[]) => console.log(response1, response2))
.catch((reason: any) => console.error(reason));
cancelAllRequests
진행중인 모든 요청에 대해 일괄적으로 취소한다 (ignoreCancel
설정된 요청은 제외).
import { cancelAllRequests } from '@mornya/restful-libs';
cancelAllRequests();
// or
cancelAllRequests('Operation canceled by user.');
isCancelled
Axios.cancel
에 의해 취소된 요청인지 확인하기 위한 메소드.
import { isCancelled } from '@mornya/restful-libs';
console.log(isCancelled(response.error)); // true or false
Usage with SWR
Next.js
기반의 프로젝트에서 SWR
라이브러리 사용시, restApi / restApis 메소드를 이용하여 아래와 예시와 같이 사용하면 된다.
라이브러리 내 SWR을 위한 메소드인
fetcher
메소드는 제거되었음.
import useSWR from 'swr';
import {
restApi,
AxiosConfig,
AxiosResponse,
AxiosError,
} from '@mornya/restful-libs';
...
function fetcher<Data> (axiosConfig: AxiosConfig) {
return async () => {
const response = await restApi<Data>(axiosConfig);
if (response) {
return response;
}
throw new Error('No responses.');
};
}
const { data, error, ...rest } = useSWR<
AxiosResponse<Payload>,
AxiosError<Error>
>(JSON.stringify(axiosConfig), fetcher(axiosConfig), {});
Change Log
프로젝트 변경사항은 CHANGELOG.md 파일 참조.
License
프로젝트 라이센스는 LICENSE 파일 참조.