request.ts 1021 B

12345678910111213141516171819202122232425262728293031323334
  1. import type { UseFetchOptions } from '#app'
  2. import type { IInterceptor, IConfig, IOption } from './interface'
  3. class Request {
  4. public baseURL: string
  5. public interceptor: IInterceptor
  6. constructor({ baseURL, interceptor }: IConfig) {
  7. this.baseURL = baseURL
  8. this.interceptor = interceptor as IInterceptor
  9. }
  10. request<T = BasicResponse>({ url, method, params, data, options }: IOption<T>): Promise<T> {
  11. const newOptions: UseFetchOptions<T> = {
  12. baseURL: this.baseURL,
  13. method,
  14. query: params,
  15. body: data,
  16. ...options,
  17. onRequest: this.interceptor?.onRequest,
  18. onRequestError: this.interceptor?.onRequestError,
  19. onResponse: this.interceptor?.onResponse,
  20. onResponseError: this.interceptor?.onResponseError,
  21. }
  22. return this.requestPipeline(url, newOptions)
  23. }
  24. // 请求管道处理具体细节
  25. requestPipeline<T = any>(url: string, options: UseFetchOptions<T>): Promise<T> {
  26. return $fetch<T>(url, options as any)
  27. }
  28. }
  29. export default Request