Created
October 12, 2022 06:03
-
-
Save kurt-liao/285c82a41ebbb98405bed823b4520457 to your computer and use it in GitHub Desktop.
Axios template in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { Method, AxiosInstance, AxiosRequestConfig } from 'axios' | |
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | |
// @ts-ignore | |
import qs from 'qs' | |
export const FORM_METHOD: Method[] = ['POST', 'post', 'PUT', 'put'] | |
export const QUERY_METHOD: Method[] = ['GET', 'get', 'DELETE', 'delete'] | |
let http: AxiosInstance = axios.create({ | |
baseURL: '/' | |
}) | |
http.interceptors.request.use( | |
(request) => { | |
if (request.method && FORM_METHOD.includes(request.method as Method)) { | |
request.data = qs.stringify(request.data) | |
} else if ( | |
request.method && | |
QUERY_METHOD.includes(request.method as Method) | |
) { | |
request.params = qs.parse(request.data) | |
request.data = undefined | |
} | |
return request | |
}, | |
(error) => { | |
return error | |
} | |
) | |
http.interceptors.response.use( | |
(response) => { | |
return Promise.resolve(response.data) | |
}, | |
(error) => { | |
const { response } = error | |
// TODO - do stuff here... | |
return error | |
} | |
) | |
export default <T>(obj: AxiosRequestConfig) => { | |
return new Promise<T>((resolve, reject) => { | |
http({ | |
url: obj.url, | |
data: obj.data, | |
method: obj.method || 'GET', | |
responseType: obj.responseType || 'json' | |
}) | |
.then((res) => { | |
// TODO - do stuff here... | |
resolve(res) | |
}) | |
.catch((err) => { | |
reject(err) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
GET
Basic
With query
POST
Basic
With data body