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

export enum ParamsType {
  REQUIRED,
  OPTIONAL
}

export const isFullUrl = (url = '') => {
  try {
    new URL(url)
    return true
  } catch (error) {
    return false
  }
}

export const getUrl = (url = '') => {
  const isFullUrlFlag = isFullUrl(url)
  const { origin } = window.location
  return isFullUrlFlag ? new URL(url) : { pathname: url, origin }
}

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) => {
  const { requestHttpType, requestParams, requestParamsBodyType, requestUrl } = request as RequestGlobalConfigType & RequestConfigType
  const { Header, Body } = requestParams
  let { Params } = requestParams
  Params = JSON.parse(JSON.stringify(Params))

  const isDynamicUrlFlag = isDynamicUrl(requestUrl || '')
  const url = getUrl(requestUrl!)
  const { origin } = url
  let { pathname } = url

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

    const paramsList = decomposeDynamicParams(pathname)
    pathname = 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
    }, pathname)

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

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

  // Object.assign(Params, { startTs: Params.date[0], endTs: Params.date[1] })
  Reflect.deleteProperty(Params, 'date')

  return defHttp.request<any>({
    url: pathname,
    baseURL: origin,
    method: requestHttpType,
    params: Params,
    data: body,
    headers: Header
  }, {
    joinPrefix: false,
    apiUrl: ''
  })
}