-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathinstance.ts
More file actions
138 lines (118 loc) · 3.63 KB
/
instance.ts
File metadata and controls
138 lines (118 loc) · 3.63 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import { isNil, isStringEmptyOrNil } from '@utils/index'
import { tableFromIPC } from 'apache-arrow'
declare global {
interface Window {
__BASE_URL__?: string
}
}
export interface ResponseWithDetail {
ok: boolean
detail?: string
}
export interface FetchOptionsWithSignal {
signal?: AbortSignal
}
export interface FetchOptions<B extends object = any> {
url: string
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
data?: B
responseType?: string
headers?: Record<string, string>
credentials?: 'omit' | 'same-origin' | 'include'
mode?: 'cors' | 'no-cors' | 'same-origin'
cache?:
| 'default'
| 'no-store'
| 'reload'
| 'no-cache'
| 'force-cache'
| 'only-if-cached'
params?: Record<string, Maybe<string | number | boolean>>
}
export async function fetchAPI<T = any, B extends object = any>(
config: FetchOptions<B>,
options?: Partial<FetchOptionsWithSignal>,
): Promise<T & ResponseWithDetail> {
const { url, method, params, data, headers, credentials, mode, cache } =
config
const hasSearchParams = Object.keys({ ...params }).length > 0
const fullUrl = url.replace(/([^:]\/)\/+/g, '$1')
const input = new URL(getUrlWithPrefix(fullUrl), window.location.origin)
if (hasSearchParams) {
const searchParams: Record<string, string> = Object.entries({
...params,
}).reduce((acc: Record<string, string>, [key, param]) => {
if (param != null) {
acc[key] = String(param)
}
return acc
}, {})
input.search = new URLSearchParams(searchParams).toString()
}
return await new Promise<T & ResponseWithDetail>((resolve, reject) => {
fetch(input, {
method,
credentials,
mode,
cache,
headers: toRequestHeaders(headers),
body: toRequestBody(data),
signal: options?.signal,
})
.then(async response => {
if (response.status === 204) return { ok: true }
const headerContentType = response.headers.get('Content-Type')
if (isNil(headerContentType))
return { ok: false, message: 'Empty response' }
if (response.status >= 400) {
try {
const json = await response.json()
json.status = json.status ?? response.status
throw json
} catch (error: any) {
throw {
message: response.statusText,
...error,
} as unknown as Error
}
}
const isEventStream = headerContentType.includes('text/event-stream')
const isApplicationJson = headerContentType.includes('application/json')
const isArrowStream = headerContentType.includes(
'application/vnd.apache.arrow.stream',
)
if (isApplicationJson) return await response.json()
if (isArrowStream) return await tableFromIPC(response)
if (isEventStream) {
const text = await response.text()
const message = text.trim().replace('data: ', '').trim()
return JSON.parse(message)
}
})
.then(resolve)
.catch(reject)
})
}
function toRequestHeaders(headers?: Record<string, string>): HeadersInit {
return {
'Content-Type': 'application/json',
...(headers ?? {}),
}
}
function toRequestBody(obj: unknown): BodyInit {
try {
return JSON.stringify(obj)
} catch (error) {
return ''
}
}
export function getUrlWithPrefix(url: string = '/'): string {
let urlWithPrefix = `${
isStringEmptyOrNil(window.__BASE_URL__) ? '/' : window.__BASE_URL__
}/${url}`
while (urlWithPrefix.includes('//')) {
urlWithPrefix = urlWithPrefix.replaceAll('//', '/')
}
return urlWithPrefix
}
export default fetchAPI