baseApi.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. if (method.toUpperCase() === "PATCH") {
  54. return {
  55. ...config,
  56. data: params,
  57. };
  58. }
  59. return config;
  60. };
  61. const apiQueryBuilder = <ParamsType extends {}, PathParamsType = {}>(
  62. method: Method = "GET",
  63. endpoint: EndpointParam<PathParamsType>
  64. ) => <ResponseType = any>(
  65. token: string,
  66. params: ParamsType,
  67. pathParams: PathParamsType
  68. ) =>
  69. axios(
  70. buildAxiosConfig(method, endpoint, token, params, pathParams)
  71. ) as AxiosPromise<ResponseType>;
  72. export { apiQueryBuilder as baseApi };
  73. export default apiQueryBuilder;