index.ts
2.6 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
88
89
90
91
92
93
94
95
96
97
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: ''
})
}