options.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import type { CreateAxiosDefaults } from 'axios';
  2. import type { IAxiosRetryConfig } from 'axios-retry';
  3. import { stringify } from 'qs';
  4. import { isHttpSuccess } from './shared';
  5. import type { RequestOption } from './type';
  6. export function createDefaultOptions<
  7. ResponseData,
  8. ApiData = ResponseData,
  9. State extends Record<string, unknown> = Record<string, unknown>
  10. >(options?: Partial<RequestOption<ResponseData, ApiData, State>>) {
  11. const opts: RequestOption<ResponseData, ApiData, State> = {
  12. defaultState: {} as State,
  13. transform: async response => response.data as unknown as ApiData,
  14. transformBackendResponse: async response => response.data as unknown as ApiData,
  15. onRequest: async config => config,
  16. isBackendSuccess: _response => true,
  17. onBackendFail: async () => {},
  18. onError: async () => {}
  19. };
  20. if (options?.transform) {
  21. opts.transform = options.transform;
  22. } else {
  23. opts.transform = options?.transformBackendResponse || opts.transform;
  24. }
  25. Object.assign(opts, options);
  26. return opts;
  27. }
  28. export function createRetryOptions(config?: Partial<CreateAxiosDefaults>) {
  29. const retryConfig: IAxiosRetryConfig = {
  30. retries: 0
  31. };
  32. Object.assign(retryConfig, config);
  33. return retryConfig;
  34. }
  35. export function createAxiosConfig(config?: Partial<CreateAxiosDefaults>) {
  36. const TEN_SECONDS = 10 * 10000;
  37. const axiosConfig: CreateAxiosDefaults = {
  38. timeout: TEN_SECONDS,
  39. headers: {
  40. 'Content-Type': 'application/json'
  41. },
  42. validateStatus: isHttpSuccess,
  43. paramsSerializer: params => {
  44. return stringify(params);
  45. }
  46. };
  47. Object.assign(axiosConfig, config);
  48. return axiosConfig;
  49. }