Skip to content

Instantly share code, notes, and snippets.

@imkarimkarim
Last active July 26, 2024 11:30
Show Gist options
  • Save imkarimkarim/b4ad8fe78447692a94bae25c93dd61f5 to your computer and use it in GitHub Desktop.
Save imkarimkarim/b4ad8fe78447692a94bae25c93dd61f5 to your computer and use it in GitHub Desktop.
axiosInstance.ts
// axiosInstance example with good logging for developers
import axios from 'axios';
import { API_PREFIX, API_URL } from '../config';
import { getUserToken } from '../auth';
const userToken = getUserToken();
const headers: any = {};
if (userToken) {
headers.Authorization = `Bearer ${userToken}`;
}
export const axiosInstance = axios.create({
headers,
baseURL: API_URL + API_PREFIX,
timeout: 20000,
});
axiosInstance.interceptors.response.use(
(res) => {
console.log(
`✅ ${res?.status} ${res?.config?.method.toUpperCase()} ${res?.config?.baseURL + res?.config?.url}`,
'\n\npayload:',
res?.config?.data,
'\n\nresponse:',
res?.data?.message || '',
res?.data,
);
// console.log(res);
return res;
},
async (err) => {
console.error(
`❌ ${err?.response?.status} ${err?.config?.method.toUpperCase()} ${err?.config?.baseURL + err?.config?.url}`,
'\n\npayload:',
err?.config?.data,
'\n\nresponse:',
err?.response?.data?.message || '',
err?.response?.data,
);
return Promise.reject(err);
},
);
@imkarimkarim
Copy link
Author

imkarimkarim commented Jul 25, 2024

Result example:

preview

@imkarimkarim
Copy link
Author

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