baseApi.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import axios from "axios";
  2. import qs from "qs";
  3. // axios.defaults.timeout = 10000;
  4. // Partial function that accepts a generic params type and returns an api method
  5. export const baseApi = <T extends {}, S = {}>(
  6. requestType: string,
  7. endpoint: ((pathParams: S) => string) | string
  8. ) => {
  9. return (token: string, params: T, pathParams: S) => {
  10. // Generate endpoint literal
  11. let endpointString: ((pathParams: S) => string) | string;
  12. if (typeof endpoint === "string") {
  13. endpointString = endpoint;
  14. } else {
  15. endpointString = endpoint(pathParams);
  16. }
  17. // Handle request type (can refactor)
  18. if (requestType === "POST") {
  19. return axios.post(endpointString, params, {
  20. headers: {
  21. Authorization: `Bearer ${token}`,
  22. },
  23. });
  24. } else if (requestType === "PUT") {
  25. return axios.put(endpointString, params, {
  26. headers: {
  27. Authorization: `Bearer ${token}`,
  28. },
  29. });
  30. } else if (requestType === "DELETE") {
  31. return axios.delete(
  32. endpointString + "?" + qs.stringify(params, { arrayFormat: "repeat" })
  33. );
  34. } else {
  35. return axios.get(endpointString, {
  36. params,
  37. paramsSerializer: function (params) {
  38. return qs.stringify(params, { arrayFormat: "repeat" });
  39. },
  40. });
  41. }
  42. };
  43. };