baseApi.tsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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(endpointString, params);
  32. } else {
  33. return axios.get(endpointString, {
  34. params,
  35. paramsSerializer: function (params) {
  36. return qs.stringify(params, { arrayFormat: "repeat" });
  37. },
  38. });
  39. }
  40. };
  41. };