Skip to content

Instantly share code, notes, and snippets.

@sidonaldson
Created December 7, 2021 12:52
Show Gist options
  • Select an option

  • Save sidonaldson/838a9c73c728b971e63527c701e1ad74 to your computer and use it in GitHub Desktop.

Select an option

Save sidonaldson/838a9c73c728b971e63527c701e1ad74 to your computer and use it in GitHub Desktop.
Axios TypeScript Dump
import axios, { AxiosError, CancelTokenSource, AxiosRequestConfig } from 'axios';
// how to overide defaults
axios.defaults.baseURL = '/';
// axios.defaults.headers.common['Content-Type'] = 'application/json'; // for all requests
// axios.defaults.headers.get['Content-Type'] = 'application/json'; // for only gets
// axios.defaults.headers.post['Content-Type'] = `multipart/mixed`; // for only posts
axios.defaults.timeout = 90000; // timeout (very high by default)
let APIToken: CancelTokenSource | null = null; // this token is used to determine if an old request should be cancelled.
function handleError(error: AxiosError, onError?: () => void) { // error helper
if (!axios.isCancel(error)) {
// if not cancelled then capture error
if (error.response) {
console.error('AXIOS Status > 2**', error.response);
} else if (error.request) {
console.error('AXIOS No Response', error.request);
} else {
console.error('AXIOS Error', error.message);
}
}
// report error here
if (onError) onError();
return Promise.reject(error);
}
// sample get, post and requests
type SampleGetResponse = {};
const sampleGet = (onError: () => void) =>
axios.get<SampleGetResponse>('/', {}).catch((error: AxiosError) => handleError(error, onError));
const sampleGetWithHeadersConfig = (onError: () => void) => {
const requestConfig: AxiosRequestConfig = { headers: { accept: 'text/plain; charset=utf-8' } };
return axios
.get<SampleGetResponse>('/', requestConfig)
.catch((error: AxiosError) => handleError(error, onError));
};
const sampleGetBlob = (onError: () => void) =>
axios
.get<Blob>('/', { responseType: 'blob' })
.catch((error: AxiosError) => handleError(error, onError));
type SamplePostResponse = {};
const samplePost = (data: string, onError: () => void) =>
axios
.post<SamplePostResponse>('/', data, { headers: { 'content-type': 'application/json' } })
.catch((error: AxiosError) => handleError(error, onError));
type SampleRequestResponse = {};
const sampleRequest = (data: string, onError: () => void) =>
axios
.request<SampleRequestResponse>({
url: '/',
method: 'POST',
headers: {},
withCredentials: false,
data,
cancelToken: APIToken ? APIToken.token : undefined,
})
.catch((error: AxiosError) => handleError(error, onError));
type SamplePromiseResponse = {};
const samplePromise = (onError: () => void) =>
new Promise((resolve) =>
axios
.request<SamplePromiseResponse>({
url: '/',
method: 'POST',
headers: {},
withCredentials: false,
data: {},
})
.then(() => resolve(true))
.catch((error: AxiosError) => resolve(handleError(error, onError))),
);
type SampleCancelableRequestResponse = {};
const sampleCancelableRequest = (data: string, onError: () => void) => {
if (APIToken) APIToken.cancel('Search canceled due to new request.');
APIToken = axios.CancelToken.source();
return axios
.request<SampleCancelableRequestResponse>({
url: '/',
method: 'POST',
headers: {},
withCredentials: false,
data,
cancelToken: APIToken ? APIToken.token : undefined,
})
.catch((error: AxiosError) => handleError(error, onError));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment