Vue3 + TS封装request请求

812 阅读1分钟

使用vueuse的createFetch方法创建request实例,添加请求拦截器。

暴露出useGet等请求方法在各个api.ts中使用。

// createFetchRequests.ts
import { unref } from 'vue';
import { createFetch } from '@vueuse/core';
// 处理请求参数函数
import parseQueryParam from './parseQueryParam';
import type { CreateFetchOptions, MaybeRef } from '@vueuse/core';

export type QueryValueType = string | number | boolean | null | undefined;

export type QueryParam = Record<string, QueryValueType | QueryValueType[]>;

export type RequestReturnType = object | number | string | boolean;

const createFetchRequests = (createFetchOptions?: CreateFetchOptions) => {
  const useFetch = createFetch(createFetchOptions);
  
  const useGet = <T extends RequestReturnType = object>(
  	url: MaybeRef<string>,
    param?: MaybeRef<QueryParam>,
  ) => useFetch<T>(`${unref(url)}${parseQueryParam(unref(param))}}`).get().json<T>();
  
  const usePost = <T extends RequestReturnType = object>(
  	url: MaybeRef<string>,
    payload?: MaybeRef<object>,
  ) => useFetch<T>(url).post(payload).json<T>();
  
  const usePut = <T extends RequestReturnType = object>(
  	url: MaybeRef<string>,
    payload?: MaybeRef<object>,
  ) => useFetch<T>(url).put(payload).json<T>();
  
  return { useFetch, useGet, usePost, usePut };
}

export default createFetchRequests;
// useFetchRequests.ts
import ElMessage from 'element-plus';
import createFetchRequests from './createFetchRequests';
import type { BeforeFetchContext } from '@vueuse/core';

const BASE_URL = 'xxx';
const REQUEST_TIME_OUT = 100000;
const UNAUTHORISED_HTTP_RESPONSE_STATUS = 401;

const { useFetch, useGet, usePost, usePut } =  createFetchRequests({
  baseUrl: BASE_URL,
  options: {
    immediate: true,
    timeout: REQUEST_TIME_OUT,
    beforeFetch(ctx) {
      const beforeFetchContext: Partial<BeforeFetchContext> = {
        ...ctx,
        options: {
          ...ctx.options,
          headers: {
            ...ctx.options.headers,
            Authorization: `Bearer ${myToken}` 
          }
        }
      }
      return beforeFetchContext;
    },
    onFetchError({ response, data, error }) {
      if(!response || response.status !== UNAUTHORISED_HTTP_RESPONSE_STATUS) {
        ElMessage.error('Error!')
      }
      return { data, error };
    }
  }
});

export { useFetch, useGet, usePost, usePut };