-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathuseApiData.ts
241 lines (218 loc) · 7.41 KB
/
useApiData.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
import { computed, reactive, toValue } from 'vue'
import { hash } from 'ohash'
import { joinURL } from 'ufo'
import type { NitroFetchOptions } from 'nitropack'
import type { MaybeRef, MaybeRefOrGetter, WatchSource } from 'vue'
import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app'
import type { ModuleOptions } from '../../module'
import { CACHE_KEY_PREFIX } from '../constants'
import { resolvePathParams } from '../openapi'
import { headersToObject, serializeMaybeEncodedBody } from '../utils'
import { isFormData } from '../form-data'
import type { EndpointFetchOptions } from '../types'
import type { FetchResponseData, FetchResponseError, FilterMethods, ParamsOption, RequestBodyOption } from '../openapi'
import { useAsyncData, useRequestHeaders, useRuntimeConfig } from '#imports'
type ComputedOptions<T> = {
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
[K in keyof T]: T[K] extends Function
? T[K]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
: T[K] extends Record<string, any>
? ComputedOptions<T[K]> | MaybeRef<T[K]>
: MaybeRef<T[K]>;
}
type ComputedMethodOption<M, P> = 'get' extends keyof P ? ComputedOptions<{ method?: M }> : ComputedOptions<{ method: M }>
export type SharedAsyncDataOptions<ResT, DataT = ResT> = Omit<AsyncDataOptions<ResT, DataT>, 'watch'> & {
/**
* Skip the Nuxt server proxy and fetch directly from the API.
* Requires `client` set to `true` in the module options.
* @remarks
* If Nuxt SSR is disabled, client-side requests are enabled by default.
* @default false
*/
client?: boolean
/**
* Cache the response for the same request.
* You can customize the cache key with the `key` option.
* @default true
*/
cache?: boolean
/**
* By default, a cache key will be generated from the request options.
* With this option, you can provide a custom cache key.
* @default undefined
*/
key?: MaybeRefOrGetter<string>
/**
* Watch an array of reactive sources and auto-refresh the fetch result when they change.
* Fetch options and URL are watched by default. You can completely ignore reactive sources by using `watch: false`.
* @default undefined
*/
watch?: (WatchSource<unknown> | object)[] | false
}
export type UseApiDataOptions<T> = Pick<
ComputedOptions<NitroFetchOptions<string>>,
| 'onRequest'
| 'onRequestError'
| 'onResponse'
| 'onResponseError'
| 'query'
| 'headers'
| 'method'
| 'retry'
| 'retryDelay'
| 'timeout'
> & {
path?: MaybeRefOrGetter<Record<string, string>>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
body?: MaybeRef<string | Record<string, any> | FormData | null>
} & SharedAsyncDataOptions<T>
export type UseApiData = <T = unknown>(
path: MaybeRefOrGetter<string>,
opts?: UseApiDataOptions<T>,
) => AsyncData<T | null, NuxtError>
export type UseOpenAPIDataOptions<
Method,
LowercasedMethod,
Params,
ResT,
DataT = ResT,
Operation = 'get' extends LowercasedMethod ? ('get' extends keyof Params ? Params['get'] : never) : LowercasedMethod extends keyof Params ? Params[LowercasedMethod] : never,
> =
ComputedMethodOption<Method, Params>
& ComputedOptions<ParamsOption<Operation>>
& ComputedOptions<RequestBodyOption<Operation>>
& Omit<AsyncDataOptions<ResT, DataT>, 'query' | 'body' | 'method'>
& SharedAsyncDataOptions<ResT, DataT>
export type UseOpenAPIData<Paths> = <
ReqT extends Extract<keyof Paths, string>,
Methods extends FilterMethods<Paths[ReqT]>,
Method extends Extract<keyof Methods, string> | Uppercase<Extract<keyof Methods, string>>,
LowercasedMethod extends Lowercase<Method> extends keyof Methods ? Lowercase<Method> : never,
DefaultMethod extends 'get' extends LowercasedMethod ? 'get' : LowercasedMethod,
ResT = FetchResponseData<Methods[DefaultMethod]>,
ErrorT = FetchResponseError<Methods[DefaultMethod]>,
DataT = ResT,
>(
path: MaybeRefOrGetter<ReqT>,
options?: UseOpenAPIDataOptions<Method, LowercasedMethod, Methods, ResT, DataT>,
autoKey?: string
) => AsyncData<DataT | null, ErrorT>
export function _useApiData<T = unknown>(
endpointId: string,
path: MaybeRefOrGetter<string>,
opts: UseApiDataOptions<T> = {},
) {
const apiParty = useRuntimeConfig().public.apiParty as Required<ModuleOptions>
const {
server,
lazy,
default: defaultFn,
transform,
pick,
watch,
immediate,
path: pathParams,
query,
headers,
method,
body,
client = apiParty.client === 'always',
cache = true,
key,
...fetchOptions
} = opts
const _path = computed(() => resolvePathParams(toValue(path), toValue(pathParams)))
const _key = computed(key === undefined
? () => CACHE_KEY_PREFIX + hash([
endpointId,
_path.value,
toValue(query),
toValue(method),
...(isFormData(toValue(body)) ? [] : [toValue(body)]),
])
: () => CACHE_KEY_PREFIX + toValue(key),
)
if (client && !apiParty.client)
throw new Error('Client-side API requests are disabled. Set "client: true" in the module options to enable them.')
const endpoint = (apiParty.endpoints || {})[endpointId]
const _fetchOptions = reactive(fetchOptions)
const _endpointFetchOptions: EndpointFetchOptions = reactive({
path: _path,
query,
headers: computed(() => ({
...headersToObject(toValue(headers)),
...(endpoint.cookies && useRequestHeaders(['cookie'])),
})),
method,
body,
})
const _asyncDataOptions: AsyncDataOptions<T> = {
server,
lazy,
default: defaultFn,
transform,
pick,
watch: watch === false
? []
: [
_endpointFetchOptions,
...(watch || []),
],
immediate,
}
let controller: AbortController | undefined
return useAsyncData<T, unknown>(
_key.value,
async (nuxt) => {
controller?.abort?.()
if (nuxt && (nuxt.isHydrating || cache) && nuxt.payload.data[_key.value])
return nuxt.payload.data[_key.value]
controller = new AbortController()
let result: T | undefined
try {
if (client) {
result = (await globalThis.$fetch<T>(_path.value, {
..._fetchOptions,
signal: controller.signal,
baseURL: endpoint.url,
method: _endpointFetchOptions.method,
query: {
...endpoint.query,
..._endpointFetchOptions.query,
},
headers: {
...(endpoint.token && { Authorization: `Bearer ${endpoint.token}` }),
...endpoint.headers,
..._endpointFetchOptions.headers,
},
body: _endpointFetchOptions.body,
})) as T
}
else {
result = (await globalThis.$fetch<T>(
joinURL('/api', apiParty.server.basePath!, endpointId),
{
..._fetchOptions,
signal: controller.signal,
method: 'POST',
body: {
..._endpointFetchOptions,
body: await serializeMaybeEncodedBody(_endpointFetchOptions.body),
} satisfies EndpointFetchOptions,
},
)) as T
}
}
catch (error) {
// Invalidate cache if request fails
if (nuxt) nuxt.payload.data[_key.value] = undefined
throw error
}
if (nuxt && cache)
nuxt.payload.data[_key.value] = result
return result
},
_asyncDataOptions,
) as AsyncData<T | null, NuxtError>
}