index.ts
2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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: ''
})
}