-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
280 lines (241 loc) · 7.86 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
import type { Ref, ShallowRef } from 'vue-demi'
import { ref, shallowRef } from 'vue-demi'
import { noop, until } from '@vueuse/shared'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, CancelTokenSource } from 'axios'
import axios, { AxiosError } from 'axios'
export interface UseAxiosReturn<T, R = AxiosResponse<T>, _D = any> {
/**
* Axios Response
*/
response: ShallowRef<R | undefined>
/**
* Axios response data
*/
data: Ref<T | undefined>
/**
* Indicates if the request has finished
*/
isFinished: Ref<boolean>
/**
* Indicates if the request is currently loading
*/
isLoading: Ref<boolean>
/**
* Indicates if the request was canceled
*/
isAborted: Ref<boolean>
/**
* Any errors that may have occurred
*/
error: ShallowRef<unknown | undefined>
/**
* Aborts the current request
*/
abort: (message?: string | undefined) => void
/**
* Alias to `abort`
*/
cancel: (message?: string | undefined) => void
/**
* Alias to `isAborted`
*/
isCanceled: Ref<boolean>
}
export interface StrictUseAxiosReturn<T, R, D> extends UseAxiosReturn<T, R, D> {
/**
* Manually call the axios request
*/
execute: (url?: string | AxiosRequestConfig<D>, config?: AxiosRequestConfig<D>) => Promise<StrictUseAxiosReturn<T, R, D>>
}
export interface EasyUseAxiosReturn<T, R, D> extends UseAxiosReturn<T, R, D> {
/**
* Manually call the axios request
*/
execute: (url: string, config?: AxiosRequestConfig<D>) => Promise<EasyUseAxiosReturn<T, R, D>>
}
export interface UseAxiosOptions<T = any> {
/**
* Will automatically run axios request when `useAxios` is used
*
*/
immediate?: boolean
/**
* Use shallowRef.
*
* @default true
*/
shallow?: boolean
/**
* Abort previous request when a new request is made.
*
* @default true
*/
abortPrevious?: boolean
/**
* Callback when error is caught.
*/
onError?: (e: unknown) => void
/**
* Callback when success is caught.
*/
onSuccess?: (data: T) => void
/**
* Initial data to use
*/
initialData?: T
/**
* Sets the state to initialState before executing the promise.
*/
resetOnExecute?: boolean
/**
* Callback when request is finished.
*/
onFinish?: () => void
}
type OverallUseAxiosReturn<T, R, D> = StrictUseAxiosReturn<T, R, D> | EasyUseAxiosReturn<T, R, D>
export function useAxios<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>, options?: UseAxiosOptions): StrictUseAxiosReturn<T, R, D> & Promise<StrictUseAxiosReturn<T, R, D>>
export function useAxios<T = any, R = AxiosResponse<T>, D = any>(url: string, instance?: AxiosInstance, options?: UseAxiosOptions): StrictUseAxiosReturn<T, R, D> & Promise<StrictUseAxiosReturn<T, R, D>>
export function useAxios<T = any, R = AxiosResponse<T>, D = any>(url: string, config: AxiosRequestConfig<D>, instance: AxiosInstance, options?: UseAxiosOptions): StrictUseAxiosReturn<T, R, D> & Promise<StrictUseAxiosReturn<T, R, D>>
export function useAxios<T = any, R = AxiosResponse<T>, D = any>(config?: AxiosRequestConfig<D>): EasyUseAxiosReturn<T, R, D> & Promise<EasyUseAxiosReturn<T, R, D>>
export function useAxios<T = any, R = AxiosResponse<T>, D = any>(instance?: AxiosInstance): EasyUseAxiosReturn<T, R, D> & Promise<EasyUseAxiosReturn<T, R, D>>
export function useAxios<T = any, R = AxiosResponse<T>, D = any>(config?: AxiosRequestConfig<D>, instance?: AxiosInstance): EasyUseAxiosReturn<T, R, D> & Promise<EasyUseAxiosReturn<T, R, D>>
/**
* Wrapper for axios.
*
* @see https://vueuse.org/useAxios
*/
export function useAxios<T = any, R = AxiosResponse<T>, D = any>(...args: any[]): OverallUseAxiosReturn<T, R, D> & Promise<OverallUseAxiosReturn<T, R, D>> {
const url: string | undefined = typeof args[0] === 'string' ? args[0] : undefined
const argsPlaceholder = typeof url === 'string' ? 1 : 0
const defaultOptions: UseAxiosOptions<T> = {
immediate: !!argsPlaceholder,
shallow: true,
abortPrevious: true,
}
let defaultConfig: AxiosRequestConfig<D> = {}
let instance: AxiosInstance = axios
let options: UseAxiosOptions<T> = defaultOptions
const isAxiosInstance = (val: any) => !!val?.request
if (args.length > 0 + argsPlaceholder) {
/**
* Unable to use `instanceof` here because of (https://github.com/axios/axios/issues/737)
* so instead we are checking if there is a `request` on the object to see if it is an
* axios instance
*/
if (isAxiosInstance(args[0 + argsPlaceholder]))
instance = args[0 + argsPlaceholder]
else
defaultConfig = args[0 + argsPlaceholder]
}
if (args.length > 1 + argsPlaceholder) {
if (isAxiosInstance(args[1 + argsPlaceholder]))
instance = args[1 + argsPlaceholder]
}
if (
(args.length === 2 + argsPlaceholder && !isAxiosInstance(args[1 + argsPlaceholder]))
|| args.length === 3 + argsPlaceholder
)
options = args[args.length - 1] || defaultOptions
const {
initialData,
shallow,
onSuccess = noop,
onError = noop,
immediate,
resetOnExecute = false,
} = options
const response = shallowRef<AxiosResponse<T>>()
const data = (shallow ? shallowRef : ref)<T>(initialData!) as Ref<T>
const isFinished = ref(false)
const isLoading = ref(false)
const isAborted = ref(false)
const error = shallowRef<unknown>()
const cancelTokenSource = axios.CancelToken.source
let cancelToken: CancelTokenSource = cancelTokenSource()
const abort = (message?: string) => {
if (isFinished.value || !isLoading.value)
return
cancelToken.cancel(message)
cancelToken = cancelTokenSource()
isAborted.value = true
isLoading.value = false
isFinished.value = false
}
const loading = (loading: boolean) => {
isLoading.value = loading
isFinished.value = !loading
}
/**
* Reset data to initialData
*/
const resetData = () => {
if (resetOnExecute)
data.value = initialData!
}
const waitUntilFinished = () =>
new Promise<OverallUseAxiosReturn<T, R, D>>((resolve, reject) => {
until(isFinished).toBe(true)
// eslint-disable-next-line ts/no-use-before-define
.then(() => error.value ? reject(error.value) : resolve(result))
})
const promise = {
then: (...args) => waitUntilFinished().then(...args),
catch: (...args) => waitUntilFinished().catch(...args),
} as Promise<OverallUseAxiosReturn<T, R, D>>
let executeCounter = 0
const execute: OverallUseAxiosReturn<T, R, D>['execute'] = (executeUrl: string | AxiosRequestConfig<D> | undefined = url, config: AxiosRequestConfig<D> = {}) => {
error.value = undefined
const _url = typeof executeUrl === 'string'
? executeUrl
: url ?? config.url
if (_url === undefined) {
error.value = new AxiosError(AxiosError.ERR_INVALID_URL)
isFinished.value = true
return promise
}
resetData()
if (options.abortPrevious)
abort()
loading(true)
executeCounter += 1
const currentExecuteCounter = executeCounter
isAborted.value = false
instance(_url, { ...defaultConfig, ...typeof executeUrl === 'object' ? executeUrl : config, cancelToken: cancelToken.token })
.then((r: any) => {
if (isAborted.value)
return
response.value = r
const result = r.data
data.value = result
onSuccess(result)
})
.catch((e: any) => {
error.value = e
onError(e)
})
.finally(() => {
options.onFinish?.()
if (currentExecuteCounter === executeCounter)
loading(false)
})
return promise
}
if (immediate && url)
(execute as StrictUseAxiosReturn<T, R, D>['execute'])()
const result = {
response,
data,
error,
isFinished,
isLoading,
cancel: abort,
isAborted,
isCanceled: isAborted,
abort,
execute,
} as OverallUseAxiosReturn<T, R, D>
return {
...result,
...promise,
}
}