index.ts 2.52 KB
import { RequestBodyEnum } from "@/enums/httpEnum"
import { ExternalRequestType, ExtraRequestConfigType } from "@/store/external/modules/extraComponentInfo.d"
import { RequestConfigType, RequestGlobalConfigType } from "@/store/modules/chartEditStore/chartEditStore.d"
import { defHttp } from "@/utils/external/http/axios"

export enum ParamsType {
  REQUIRED,
  OPTIONAL
}

const getOriginUrl = (originUrl: string) => {
  const locationUrl = 'localhost'
  return originUrl === locationUrl ? location.origin : originUrl
}

const regOptionalParams = /(?={\?)/g
const regDynamicParams = /(?={).+?(?<=})/g

export const isDynamicUrl = (url: string) => {
  regDynamicParams.lastIndex = 0

  return regDynamicParams.test(url)
}

export const decomposeDynamicParams = (url: string) => {
  regDynamicParams.lastIndex = 0
  regOptionalParams.lastIndex = 0

  return Array.from((url || '').matchAll(regDynamicParams), ([item]) => {
    return {
      type: regOptionalParams.test(item) ? ParamsType.OPTIONAL : ParamsType.REQUIRED,
      originValue: item,
      value: item.replaceAll(/[{}?]/g, '').split(',')
    }
  })
}

export const customRequest = async (request: RequestConfigType) => {
  console.log(request)
  const { requestHttpType, requestParams, requestParamsBodyType, requestOriginUrl } = request as ExtraRequestConfigType
  let { requestUrl } = request as ExtraRequestConfigType
  const { Header, Body } = requestParams
  let { Params } = requestParams
  Params = JSON.parse(JSON.stringify(Params))
  const isDynamicUrlFlag = isDynamicUrl(requestUrl || '')



  if (isDynamicUrlFlag) {
    requestUrl = decodeURI(requestUrl || '')

    const paramsList = decomposeDynamicParams(requestUrl)
    requestUrl = paramsList.reduce((prev, next) => {
      const { type, value, originValue } = next
      if (type === ParamsType.REQUIRED) {
        value.forEach(key => {
          prev = prev.replace(key, Reflect.get(Params, key))
          Reflect.deleteProperty(Params, key)
        })
      }

      if (type === ParamsType.OPTIONAL) {
        prev = prev.replace(originValue, '')
      }

      return prev
    }, requestUrl)

    requestUrl = requestUrl.replaceAll(/[{}?]/g, '')
  }

  const body = Body[requestParamsBodyType as Exclude<'NONE', keyof typeof RequestBodyEnum>]

  Reflect.deleteProperty(Params, 'date')
  console.log(Header)
  return defHttp.request<any>({
    url: requestUrl,
    baseURL: getOriginUrl(requestOriginUrl!),
    method: requestHttpType,
    params: Params,
    data: body,
    headers: Header
  }, {
    joinPrefix: false,
    apiUrl: ''
  })
}