79 lines
2.3 KiB
TypeScript
79 lines
2.3 KiB
TypeScript
import { merge } from 'lodash'
|
|
import type { AxiosError, AxiosInstance, AxiosRequestConfig, CancelTokenSource } from 'axios'
|
|
import axios from 'axios'
|
|
import { getError, parseResponse } from './parse'
|
|
import { HTTP_METHODS } from '~/constants'
|
|
import { config } from '~/configs'
|
|
import type { RequestOptions } from '~/types/models/requestOptions'
|
|
|
|
const TIMEOUT = 180000
|
|
const { CancelToken } = axios
|
|
const { API_BASE_URL } = config
|
|
const axiosInstance = axios.create({
|
|
baseURL: API_BASE_URL,
|
|
timeout: TIMEOUT,
|
|
})
|
|
const axiosInstanceSource = CancelToken.source()
|
|
|
|
export function setAxiosRequestConfig(
|
|
api: AxiosInstance, { token: cancelToken }: CancelTokenSource, method: string, url: string, options?: RequestOptions,
|
|
) {
|
|
const requestConfig = merge({
|
|
url,
|
|
cancelToken,
|
|
method,
|
|
}, options)
|
|
|
|
// eslint-disable-next-line no-console
|
|
console.log(requestConfig)
|
|
|
|
return api(requestConfig as AxiosRequestConfig)
|
|
}
|
|
|
|
/**
|
|
* Attach common codes before and after api call.
|
|
* 1. Add cancel token for cancelling all requests.
|
|
* 2. Parse basic response
|
|
* @param {object} api
|
|
* @param {object} source
|
|
* @param {function} parse
|
|
* @returns {*}
|
|
*/
|
|
export function getHttpMethodsWithCancel(
|
|
api = axiosInstance,
|
|
source = axiosInstanceSource,
|
|
parse = parseResponse,
|
|
) {
|
|
const getApiPromise = (method: string, url: string, options?: RequestOptions) =>
|
|
setAxiosRequestConfig(api, source, method, url, options)
|
|
.then(parse)
|
|
.catch((error: AxiosError) => {
|
|
getError(error)
|
|
})
|
|
|
|
return {
|
|
get(url: string, options?: RequestOptions) {
|
|
return getApiPromise(HTTP_METHODS.GET, url, options)
|
|
},
|
|
post(url: string, options?: RequestOptions) {
|
|
return getApiPromise(HTTP_METHODS.POST, url, options)
|
|
},
|
|
put(url: string, options?: RequestOptions) {
|
|
return getApiPromise(HTTP_METHODS.PUT, url, options)
|
|
},
|
|
/**
|
|
* Axios's delete accepts url and configs only.
|
|
* If you want to send data with delete, use configs.data
|
|
* @see https://github.com/axios/axios/issues/897#issuecomment-343715381
|
|
*/
|
|
delete(url: string, options?: RequestOptions) {
|
|
return getApiPromise(HTTP_METHODS.DELETE, url, options)
|
|
},
|
|
cancelAPIs() {
|
|
source.cancel('API is canceled by cancelAPIs')
|
|
},
|
|
}
|
|
}
|
|
|
|
export default getHttpMethodsWithCancel()
|