forked from vitest-dev/vitest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
463 lines (386 loc) · 11.5 KB
/
index.ts
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import { Ref, ref, unref, watch, computed, ComputedRef, shallowRef, isRef } from 'vue-demi'
import { Fn, MaybeRef, containsProp, createEventHook, EventHookOn } from '@vueuse/shared'
import { defaultWindow } from '../_configurable'
interface UseFetchReturn<T> {
/**
* Indicates if the fetch request has finished
*/
isFinished: Ref<boolean>
/**
* The statusCode of the HTTP fetch response
*/
statusCode: Ref<number | null>
/**
* The raw response of the fetch response
*/
response: Ref<Response | null>
/**
* Any fetch errors that may have occurred
*/
error: Ref<any>
/**
* The fetch response body, may either be JSON or text
*/
data: Ref<T | null>
/**
* Indicates if the request is currently being fetched.
*/
isFetching: Ref<boolean>
/**
* Indicates if the fetch request is able to be aborted
*/
canAbort: ComputedRef<boolean>
/**
* Indicates if the fetch request was aborted
*/
aborted: Ref<boolean>
/**
* Abort the fetch request
*/
abort: Fn
/**
* Manually call the fetch
* (default not throwing error)
*/
execute: (throwOnFailed?: boolean) => Promise<any>
/**
* Fires after the fetch request has finished
*/
onFetchResponse: EventHookOn<Response>
/**
* Fires after a fetch request error
*/
onFetchError: EventHookOn
/**
* Fires after a fetch has completed
*/
onFetchFinally: EventHookOn
// methods
get(): UseFetchReturn<T>
post(payload?: MaybeRef<unknown>, type?: string): UseFetchReturn<T>
put(payload?: MaybeRef<unknown>, type?: string): UseFetchReturn<T>
delete(payload?: MaybeRef<unknown>, type?: string): UseFetchReturn<T>
// type
json<JSON = any>(): UseFetchReturn<JSON>
text(): UseFetchReturn<string>
blob(): UseFetchReturn<Blob>
arrayBuffer(): UseFetchReturn<ArrayBuffer>
formData(): UseFetchReturn<FormData>
}
type DataType = 'text' | 'json' | 'blob' | 'arrayBuffer' | 'formData'
type HttpMethod = 'get' | 'post' | 'put' | 'delete'
const payloadMapping: Record<string, string> = {
json: 'application/json',
text: 'text/plain',
formData: 'multipart/form-data',
}
export interface BeforeFetchContext {
/**
* The computed url of the current request
*/
url: string
/**
* The request options of the current request
*/
options: RequestInit
/**
* Cancels the current request
*/
cancel: Fn
}
export interface AfterFetchContext<T = any> {
response: Response
data: T | null
}
export interface UseFetchOptions {
/**
* Fetch function
*/
fetch?: typeof window.fetch
/**
* Will automatically run fetch when `useFetch` is used
*
* @default true
*/
immediate?: boolean
/**
* Will automatically refetch when:
* - the URL is changed if the URL is a ref
* - the payload is changed if the payload is a ref
*
* @default false
*/
refetch?: MaybeRef<boolean>
/**
* Initial data before the request finished
*
* @default null
*/
initialData?: any
/**
* Will run immediately before the fetch request is dispatched
*/
beforeFetch?: (ctx: BeforeFetchContext) => Promise<Partial<BeforeFetchContext> | void> | Partial<BeforeFetchContext> | void
/**
* Will run immediately after the fetch request is returned.
* Runs after any 2xx response
*/
afterFetch?: (ctx: AfterFetchContext) => Promise<Partial<AfterFetchContext>> | Partial<AfterFetchContext>
}
export interface CreateFetchOptions {
/**
* The base URL that will be prefixed to all urls
*/
baseUrl?: MaybeRef<string>
/**
* Default Options for the useFetch function
*/
options?: UseFetchOptions
/**
* Options for the fetch request
*/
fetchOptions?: RequestInit
}
/**
* !!!IMPORTANT!!!
*
* If you update the UseFetchOptions interface, be sure to update this object
* to include the new options
*/
function isFetchOptions(obj: object): obj is UseFetchOptions {
return containsProp(obj, 'immediate', 'refetch', 'initialData', 'beforeFetch', 'afterFetch')
}
function headersToObject(headers: HeadersInit | undefined) {
if (headers instanceof Headers)
return Object.fromEntries([...headers.entries()])
return headers
}
export function createFetch(config: CreateFetchOptions = {}) {
const _options = config.options || {}
const _fetchOptions = config.fetchOptions || {}
function useFactoryFetch(url: MaybeRef<string>, ...args: any[]) {
const computedUrl = computed(() => config.baseUrl
? joinPaths(unref(config.baseUrl), unref(url))
: unref(url),
)
let options = _options
let fetchOptions = _fetchOptions
// Merge properties into a single object
if (args.length > 0) {
if (isFetchOptions(args[0])) {
options = { ...options, ...args[0] }
}
else {
fetchOptions = {
...fetchOptions,
...args[0],
headers: {
...(headersToObject(fetchOptions.headers) || {}),
...(headersToObject(args[0].headers) || {}),
},
}
}
}
if (args.length > 1 && isFetchOptions(args[1]))
options = { ...options, ...args[1] }
return useFetch(computedUrl, fetchOptions, options)
}
return useFactoryFetch as typeof useFetch
}
export function useFetch<T>(url: MaybeRef<string>): UseFetchReturn<T>
export function useFetch<T>(url: MaybeRef<string>, useFetchOptions: UseFetchOptions): UseFetchReturn<T>
export function useFetch<T>(url: MaybeRef<string>, options: RequestInit, useFetchOptions?: UseFetchOptions): UseFetchReturn<T>
export function useFetch<T>(url: MaybeRef<string>, ...args: any[]): UseFetchReturn<T> {
const supportsAbort = typeof AbortController === 'function'
let fetchOptions: RequestInit = {}
let options: UseFetchOptions = { immediate: true, refetch: false }
type InternalConfig = {method: HttpMethod; type: DataType; payload: unknown; payloadType?: string}
const config: InternalConfig = {
method: 'get',
type: 'text' as DataType,
payload: undefined as unknown,
}
if (args.length > 0) {
if (isFetchOptions(args[0]))
options = { ...options, ...args[0] }
else
fetchOptions = args[0]
}
if (args.length > 1) {
if (isFetchOptions(args[1]))
options = { ...options, ...args[1] }
}
const {
fetch = defaultWindow?.fetch,
initialData,
} = options
// Event Hooks
const responseEvent = createEventHook<Response>()
const errorEvent = createEventHook<any>()
const finallyEvent = createEventHook<any>()
const isFinished = ref(false)
const isFetching = ref(false)
const aborted = ref(false)
const statusCode = ref<number | null>(null)
const response = shallowRef<Response | null>(null)
const error = ref<any>(null)
const data = shallowRef<T | null>(initialData)
const canAbort = computed(() => supportsAbort && isFetching.value)
let controller: AbortController | undefined
const abort = () => {
if (supportsAbort && controller)
controller.abort()
}
const loading = (isLoading: boolean) => {
isFetching.value = isLoading
isFinished.value = !isLoading
}
const execute = async(throwOnFailed = false) => {
loading(true)
error.value = null
statusCode.value = null
aborted.value = false
controller = undefined
if (supportsAbort) {
controller = new AbortController()
controller.signal.onabort = () => aborted.value = true
fetchOptions = {
...fetchOptions,
signal: controller.signal,
}
}
const defaultFetchOptions: RequestInit = {
method: config.method,
headers: {},
}
if (config.payload) {
const headers = headersToObject(defaultFetchOptions.headers) as Record<string, string>
if (config.payloadType)
headers['Content-Type'] = payloadMapping[config.payloadType] ?? config.payloadType
defaultFetchOptions.body = config.payloadType === 'json' ? JSON.stringify(unref(config.payload)) : unref(config.payload) as BodyInit
}
let isCanceled = false
const context: BeforeFetchContext = { url: unref(url), options: fetchOptions, cancel: () => { isCanceled = true } }
if (options.beforeFetch)
Object.assign(context, await options.beforeFetch(context))
if (isCanceled || !fetch) {
loading(false)
return Promise.resolve()
}
return new Promise((resolve, reject) => {
fetch(
context.url,
{
...defaultFetchOptions,
...context.options,
headers: {
...headersToObject(defaultFetchOptions.headers),
...headersToObject(context.options?.headers),
},
},
)
.then(async(fetchResponse) => {
response.value = fetchResponse
statusCode.value = fetchResponse.status
let responseData = await fetchResponse[config.type]()
if (options.afterFetch)
({ data: responseData } = await options.afterFetch({ data: responseData, response: fetchResponse }))
data.value = responseData as any
// see: https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
if (!fetchResponse.ok)
throw new Error(fetchResponse.statusText)
responseEvent.trigger(fetchResponse)
resolve(fetchResponse)
})
.catch((fetchError) => {
error.value = fetchError.message || fetchError.name
errorEvent.trigger(fetchError)
if (throwOnFailed)
reject(fetchError)
else
resolve(undefined)
})
.finally(() => {
loading(false)
finallyEvent.trigger(null)
})
})
}
watch(
() => [
unref(url),
unref(options.refetch),
],
() => unref(options.refetch) && execute(),
{ deep: true },
)
const shell: UseFetchReturn<T> = {
isFinished,
statusCode,
response,
error,
data,
isFetching,
canAbort,
aborted,
abort,
execute,
onFetchResponse: responseEvent.on,
onFetchError: errorEvent.on,
onFetchFinally: finallyEvent.on,
// method
get: setMethod('get'),
put: setMethod('put'),
post: setMethod('post'),
delete: setMethod('delete'),
// type
json: setType('json'),
text: setType('text'),
blob: setType('blob'),
arrayBuffer: setType('arrayBuffer'),
formData: setType('formData'),
}
function setMethod(method: HttpMethod) {
return (payload?: unknown, payloadType?: string) => {
if (!isFetching.value) {
config.method = method
config.payload = payload
config.payloadType = payloadType
// watch for payload changes
if (isRef(config.payload)) {
watch(
() => [
unref(config.payload),
unref(options.refetch),
],
() => unref(options.refetch) && execute(),
{ deep: true },
)
}
// Set the payload to json type only if it's not provided and a literal object is provided
// The only case we can deduce the content type and `fetch` can't
if (!payloadType && unref(payload) && Object.getPrototypeOf(unref(payload)) === Object.prototype)
config.payloadType = 'json'
return shell as any
}
return undefined
}
}
function setType(type: DataType) {
return () => {
if (!isFetching.value) {
config.type = type
return shell as any
}
return undefined
}
}
if (options.immediate)
setTimeout(execute, 0)
return shell
}
function joinPaths(start: string, end: string): string {
if (!start.endsWith('/') && !end.startsWith('/'))
return `${start}/${end}`
return `${start}${end}`
}