Skip to content

Instantly share code, notes, and snippets.

@brunapereira
Last active July 25, 2023 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunapereira/3dd32c9be854e97404b3138f77a68ac1 to your computer and use it in GitHub Desktop.
Save brunapereira/3dd32c9be854e97404b3138f77a68ac1 to your computer and use it in GitHub Desktop.
type AxiosConfigWithMetadata = InternalAxiosRequestConfig & {
metadata?: {
axiosId: string
}
}
const interceptRequest = (config: AxiosConfigWithMetadata) => {
const axiosId = uuidV4();
logger.debug("outbound request", {
baseUrl: config.baseURL,
method: config.method,
data: config.data,
params: config.params,
url: config.url,
headers: config.headers,
axiosId,
});
config.metadata = {
axiosId: axiosId,
};
return config;
};
const interceptSuccessResponse = (response: AxiosResponse) => {
logger.debug("outbound response success", {
baseUrl: response.config.baseURL,
url: response.config.url,
status: `${response.status}:${response.statusText}`,
headers: response.headers,
body: response.data,
axiosId: (response.config as AxiosConfigWithMetadata).metadata?.axiosId,
});
return response;
};
const interceptorErrorResponse = (error: any) => {
if (error instanceof Error) {
const axiosError = error as AxiosError;
logger.debug("outbound response failure", {
baseUrl: axiosError?.response?.config.baseURL,
url: axiosError?.response?.config.url,
status: axiosError.response?.status,
headers: axiosError.response?.headers,
body: axiosError.response?.data,
axiosId: (axiosError?.response?.config as AxiosConfigWithMetadata).metadata?.axiosId,
});
}
return Promise.reject(error);
};
export const createAxiosInstance = (baseURL: string, headers: Record<string, string>) => {
const axiosInstance = Axios.create({baseURL: baseURL, headers});
axiosInstance.interceptors.request.use(interceptRequest);
axiosInstance.interceptors.response.use(interceptSuccessResponse, interceptorErrorResponse);
return axiosInstance;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment