baseApi.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import axios, { AxiosPromise, AxiosRequestConfig, Method } from "axios";
  2. import qs from "qs";
  3. type EndpointParam<PathParamsType> =
  4. | string
  5. | ((pathParams: PathParamsType) => string);
  6. type BuildAxiosConfigFunction = (
  7. method: Method,
  8. endpoint: EndpointParam<unknown>,
  9. token: string,
  10. params: unknown,
  11. pathParams: unknown
  12. ) => AxiosRequestConfig;
  13. const buildAxiosConfig: BuildAxiosConfigFunction = (
  14. method,
  15. endpoint,
  16. token,
  17. params,
  18. pathParams
  19. ) => {
  20. const config: AxiosRequestConfig = {
  21. method,
  22. url: typeof endpoint === "function" ? endpoint(pathParams) : endpoint,
  23. };
  24. if (method.toUpperCase() === "POST") {
  25. return {
  26. ...config,
  27. data: params,
  28. };
  29. }
  30. if (method.toUpperCase() === "PUT") {
  31. return {
  32. ...config,
  33. data: params,
  34. };
  35. }
  36. if (method.toUpperCase() === "DELETE") {
  37. const queryParams = qs.stringify(params, {
  38. arrayFormat: "repeat",
  39. });
  40. return {
  41. ...config,
  42. url: `${config.url}?${queryParams}`,
  43. };
  44. }
  45. if (method.toUpperCase() === "GET") {
  46. return {
  47. ...config,
  48. params: params,
  49. paramsSerializer: (params) =>
  50. qs.stringify(params, { arrayFormat: "repeat" }),
  51. };
  52. }
  53. return config;
  54. };
  55. const apiQueryBuilder = <ParamsType extends {}, PathParamsType = {}>(
  56. method: Method = "GET",
  57. endpoint: EndpointParam<PathParamsType>
  58. ) => <ResponseType = any>(
  59. token: string,
  60. params: ParamsType,
  61. pathParams: PathParamsType
  62. ) =>
  63. axios(
  64. buildAxiosConfig(method, endpoint, token, params, pathParams)
  65. ) as AxiosPromise<ResponseType>;
  66. export { apiQueryBuilder as baseApi };
  67. export default apiQueryBuilder;