Skip to content

Instantly share code, notes, and snippets.

@kurt-liao
Created October 12, 2022 06:03
Show Gist options
  • Save kurt-liao/285c82a41ebbb98405bed823b4520457 to your computer and use it in GitHub Desktop.
Save kurt-liao/285c82a41ebbb98405bed823b4520457 to your computer and use it in GitHub Desktop.
Axios template in typescript
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)
})
})
}
@kurt-liao
Copy link
Author

Usage

GET

Basic

customAxios<Array<string>>({
  url: 'https://example.com'
})

No need to add method since GET is the default.

With query

customAxios<Array<string>>({
  url: 'https://example.com',
  data: {
    param1: 'xxx',
    param2: 'yyy'
  }
})

POST

Basic

customAxios<Array<string>>({
  method: 'POST',
  url: 'https://example.com'
})

'POST' or 'post' are both valid.

With data body

customAxios<Array<string>>({
  method: 'POST',
  url: 'https://example.com',
  data: {
    param1: 'xxx',
    param2: 'yyy'
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment