UNPKG

@mornya/restful-libs

Version:

The project of wrapped library for RESTful API processing module.

280 lines (240 loc) 9.36 kB
# RESTful Libs ![npm](https://img.shields.io/npm/v/@mornya/restful-libs) ![node](https://img.shields.io/node/v/@mornya/restful-libs) ![types](https://img.shields.io/npm/types/@mornya/restful-libs) ![downloads](https://img.shields.io/npm/dw/@mornya/restful-libs) ![license](https://img.shields.io/npm/l/@mornya/restful-libs) The project of wrapped library for RESTful API processing module > This project has been created by [Vessel CLI](https://www.npmjs.com/package/@mornya/vessel). For a simple and quick reference about it, click [here](https://mornya.github.io/documents/guide/vessel.md). ## About Axios, AxiosCancel 및 AxiosRetry 등의 모듈을 이용하여 RESTful API 요청에 대한 일괄적인 프로세스를 수행. SPA / SSR / Node.js 등 모든 프로젝트에서 사용가능하다. ## Installation 해당 모듈을 사용할 프로젝트에서는 아래와 같이 설치한다. ```bash $ npm install --save @mornya/restful-libs or $ yarn add @mornya/restful-libs ``` ## Usage 최초 랜더링 되는 앱에 아래와 같이 `axiosDefaultConfig` 메소드를 이용하여 설정 부분을 추가해주면 된다. ### `Vue.js` example ```vue <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> ``` ### `React.js` example ```typescript jsx 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하여 사용한다. ```typescript import { axios } from '@mornya/restful-libs'; ``` ## Configuration `axiosDefaultConfig` 메소드는 이미 오버라이드 된 axios 기본 설정을 사용자에 맞게 오버라이드 시켜줄 수 있다. interface 선언과 아래 샘플을 참고하면 된다. ```typescript import { axiosDefaultConfig, AxiosDefaultConfig } from '@mornya/restful-libs'; const axiosConfig: AxiosDefaultConfig = { // ===== 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 로그에 전체 항목 표시 여부 truncateLogThreshold: 0, // 출력 로그메시지가 길면 자르기 (0:disabled, 1~:한계치) isThrowsOnError: true, // response 오류 발생시 throw 할 것인지 여부 isCancelDuplicateRequests: false, // 동일 request를 중복으로 호출시 취소 여부 isCacheable: true, // LRU 캐시 기능 사용 여부 requestsThreshold: 100, // 최대 동시 호출 request 갯수 제한 'axios-retry': { // 요청 실패 혹은 오류시 재시도를 위한 axios-retry 모듈에 대한 옵션이며, // 본 라이브러리 기본 설정으로 50X 오류 발생시에만 retry 하도록 설정되어 있다. // (retryCondition 설정으로 변경가능) // 관련 내용은 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', }, onAuthorize: (config) => { // 요청 전 헤더에 공통 인증을 위한 설정이 필요한 경우 사용. // 해당 메소드 미지정시, "accessToken" 이름으로 지정된 로컬스토리지 값으로 // 요청 헤더에 "Authorization: 'Bearer xxxxxxxxxx'"가 추가 된다. }, 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 본 패키지에는 아래와 같은 모듈들을 포함한다.<br> 제공되는 모듈과 메소드 사용법 등은 코드 스니핏을 참고한다. ### AxiosLib module 기본 모듈이며, 다음과 같은 메소드들을 제공한다. #### `axiosDefaultConfig` axios 라이브러리 설정 및 restful 라이브러리 설정으로 초기화 한다. > 위의 Configuration 항목 참조 #### `restApi` axios 라이브러리로 요청을 수행한다. Request 설정 옵션은 아래와 같다. * `ignoreCancel`: 일괄적인 요청취소에 대해 무시하도록 설정한다. * `ignoreResponseCallback`: 요청에 대한 응답 처리 콜백(onResponse)를 무시해야 할 경우에 사용한다 (예외사항이 있는 API 등 호출시). ```typescript 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, ignoreResponseCallback: true, cache: true, // "isCacheable" 옵션이 true일 경우 캐싱 처리 시도 }) .then((response: AxiosResponse) => console.log(response)) .catch((reason: any) => console.error(reason)); ``` #### `restApis` axios 라이브러리로 여러 요청을 병렬로 수행한다. ```typescript import { restApis, AxiosResponse } from '@mornya/restful-libs'; restApis([ { method: 'POST', url: '/mock/test1', data: { test: 'test1' }, }, { method: 'POST', url: '/mock/test2', data: { test: 'test2' }, cache: true, // "isCacheable" 옵션이 true일 경우 캐싱 처리 시도 }, ]) .then(([response1, response2]: AxiosResponse[]) => console.log(response1, response2)) .catch((reason: any) => console.error(reason)); ``` #### `cancelAllRequests` 진행중인 모든 요청에 대해 일괄적으로 취소한다 (`ignoreCancel` 설정된 요청은 제외). ```typescript import { cancelAllRequests } from '@mornya/restful-libs'; cancelAllRequests(); // or cancelAllRequests('Operation canceled by user.'); ``` #### `isCancelled` `Axios.cancel`에 의해 취소된 요청인지 확인하기 위한 메소드. ```typescript import { isCancelled } from '@mornya/restful-libs'; console.log(isCancelled(response.error)); // true or false ``` ### Usage with SWR `Next.js` 기반의 프로젝트에서 `SWR` 라이브러리 사용시, restApi / restApis 메소드를 이용하여 아래와 예시와 같이 사용하면 된다. ```typescript jsx 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](CHANGELOG.md) 파일 참조. ## License 프로젝트 라이센스는 [LICENSE](LICENSE) 파일 참조.