axios.ts 903 B

1234567891011121314151617181920212223242526272829303132333435
  1. // eslint-disable-next-line no-restricted-imports
  2. import axios from 'axios';
  3. import parseISO from 'date-fns/parseISO';
  4. import isIsoDate from 'is-iso-date';
  5. const customAxios = axios.create({
  6. headers: {
  7. 'X-Requested-With': 'XMLHttpRequest',
  8. 'Content-Type': 'application/json',
  9. },
  10. });
  11. // add an interceptor to convert ISODate
  12. const convertDates = (body: any): void => {
  13. if (body === null || body === undefined || typeof body !== 'object') {
  14. return body;
  15. }
  16. for (const key of Object.keys(body)) {
  17. const value = body[key];
  18. if (isIsoDate(value)) {
  19. body[key] = parseISO(value);
  20. }
  21. else if (typeof value === 'object') {
  22. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  23. convertDates(value);
  24. }
  25. }
  26. };
  27. customAxios.interceptors.response.use((response) => {
  28. convertDates(response.data);
  29. return response;
  30. });
  31. export default customAxios;