types.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
  2. // request 方法 opts 参数的接口
  3. export interface IRequestOptions extends AxiosRequestConfig {
  4. requestInterceptors?: IRequestInterceptorTuple[];
  5. responseInterceptors?: IResponseInterceptorTuple[];
  6. [key: string]: any;
  7. }
  8. export interface IRequestOptionsWithResponse extends IRequestOptions {
  9. getResponse: true;
  10. }
  11. export interface IRequestOptionsWithoutResponse extends IRequestOptions {
  12. getResponse: false;
  13. }
  14. export interface IRequest {
  15. <T = any>(url: string, opts: IRequestOptionsWithResponse): Promise<AxiosResponse<T>>;
  16. <T = any>(url: string, opts: IRequestOptionsWithoutResponse): Promise<T>;
  17. <T = any>(url: string, opts?: IRequestOptions): Promise<T>; // getResponse 默认是 false, 因此不提供该参数时,只返回 data,不提供 opts 时,默认使用 'GET' method,并且默认返回 data
  18. }
  19. export type RequestError = AxiosError | Error;
  20. export interface IErrorHandler {
  21. (error: RequestError, opts: IRequestOptions): void;
  22. }
  23. export type WithPromise<T> = T | Promise<T>;
  24. export type IRequestInterceptorAxios = (config: IRequestOptions) => WithPromise<IRequestOptions>;
  25. export type IRequestInterceptorRequest = (
  26. url: string,
  27. config: IRequestOptions
  28. ) => WithPromise<{ url: string; options: IRequestOptions }>;
  29. export type IRequestInterceptor = IRequestInterceptorAxios | IRequestInterceptorRequest;
  30. export type IErrorInterceptor = (error: Error) => Promise<Error>;
  31. export type IResponseInterceptor = <T = any>(
  32. response: AxiosResponse<T>
  33. ) => WithPromise<AxiosResponse<T>>;
  34. export type IRequestInterceptorTuple =
  35. | [IRequestInterceptor, IErrorInterceptor]
  36. | [IRequestInterceptor]
  37. | IRequestInterceptor;
  38. export type IResponseInterceptorTuple =
  39. | [IResponseInterceptor, IErrorInterceptor]
  40. | [IResponseInterceptor]
  41. | IResponseInterceptor;
  42. export interface RequestConfig<T = any> extends IRequestOptions {
  43. skipErrorHandler?: boolean;
  44. encryption?: {
  45. enabled: boolean;
  46. key: string;
  47. };
  48. errorConfig?: {
  49. errorHandler?: IErrorHandler;
  50. errorThrower?: (res: T) => void;
  51. };
  52. }