baseApi.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. const AuthHeaders = {
  25. Authorization: `Bearer ${token}`,
  26. };
  27. if (method.toUpperCase() === "POST") {
  28. return {
  29. ...config,
  30. data: params,
  31. headers: AuthHeaders,
  32. };
  33. }
  34. if (method.toUpperCase() === "PUT") {
  35. return {
  36. ...config,
  37. data: params,
  38. headers: AuthHeaders,
  39. };
  40. }
  41. if (method.toUpperCase() === "DELETE") {
  42. const queryParams = qs.stringify(params, {
  43. arrayFormat: "repeat",
  44. });
  45. return {
  46. ...config,
  47. url: `${config.url}?${queryParams}`,
  48. };
  49. }
  50. if (method.toUpperCase() === "GET") {
  51. return {
  52. ...config,
  53. params: params,
  54. paramsSerializer: (params) =>
  55. qs.stringify(params, { arrayFormat: "repeat" }),
  56. };
  57. }
  58. return config;
  59. };
  60. const apiQueryBuilder = <ParamsType extends {}, PathParamsType = {}>(
  61. method: Method = "GET",
  62. endpoint: EndpointParam<PathParamsType>
  63. ) => <ResponseType = any>(
  64. token: string,
  65. params: ParamsType,
  66. pathParams: PathParamsType
  67. ) =>
  68. axios(
  69. buildAxiosConfig(method, endpoint, token, params, pathParams)
  70. ) as AxiosPromise<ResponseType>;
  71. export { apiQueryBuilder as baseApi };
  72. export default apiQueryBuilder;