An axios instance builder for use on client or server side with common features pre-configured:
By default, axios does not configure a timeout or a cancellation timeout. However, axios-http-builder
sets both to 2 seconds by default, which remains configurable.
axios-http-builder
also includes an optional exception handler.
npm i -save axios-http-builder
To use the default configuration, instantiate the axios instance with buildHttpClient
and then use as normal:
import { buildHttpClient } from 'axios-http-builder';
const httpClient = buildHttpClient();
await httpClient.get('https://myservice/entity');
buildHttpClient
takes a CreateAxiosDefaults
object, so you can use any of axios' options as normal:
import { buildHttpClient } from 'axios-http-builder';
const httpClient = buildHttpClient({ baseURL: 'https://myservice' });
await httpClient.get('/entity');
The axios-http-builder
defaults are applied to the configuration, unless you specify your own:
import { buildHttpClient, newAbortSignal } from 'axios-http-builder';
const httpClient = buildHttpClient({ baseURL: 'https://myservice' , timeout: 3000, signal: newAbortSignal(3000)});
await httpClient.get('/entity');
The timeout and cancellation timeout can also be set using environment variables:
AXIOS_TIMEOUT=3000
AXIOS_CANCEL_TIMEOUT=3000
axios-http-builder
includes an optional exception handling function:
import { buildHttpClient, handleException } from 'axios-http-builder';
const httpClient = buildHttpClient({ baseURL: 'https://myservice' });
try {
await httpClient.get('/entity');
} catch (e: any) {
const { isAxiosError, message, axiosError, data, statusCode, statusText } = handleException(e);
...
}
handleException
analyses the exception to determine whether it is an AxiosError
, Error
or something else. It always returns isAxiosError
and message
. The other values are only returned if the exception is an AxiosError
. The intention is to provide a boilerplate function which handles AxiosError
and other exceptions and always return the right exception message.
-
isAxiosError
- whether or not the exception is anAxiosError
-
message
- the exception message -
axiosError
- theAxiosError
object. Although this is the same as the original exception, the type of the original exception is not recognised by the compiler, as it could beError
or something else. Only returned forAxiosError
s -
data
- the body of the response. Only returned forAxiosError
s -
statusCode
- the http status code. Only returned forAxiosError
s -
statusText
- the http status text. Only returned forAxiosError
s