This repository was archived by the owner on Dec 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathfetch.ts
387 lines (327 loc) · 9.88 KB
/
fetch.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
import {
ref,
isRef,
onBeforeMount,
onServerPrefetch,
reactive,
set,
} from '@vue/composition-api'
import {
globalContext,
globalNuxt,
isFullStatic,
} from '@nuxtjs/composition-api/dist/runtime/globals'
import type { NuxtApp } from '@nuxt/types/app'
import { getCurrentInstance, ComponentInstance } from './utils'
const nuxtState = process.client && (window as any)[globalContext]
function normalizeError(err: any) {
let message: string
if (!(err.message || typeof err === 'string')) {
try {
message = JSON.stringify(err, null, 2)
} catch (e) {
message = `[${err.constructor.name}]`
}
} else {
message = err.message || err
}
return {
...err,
message,
statusCode:
err.statusCode ||
err.status ||
(err.response && err.response.status) ||
500,
}
}
function createGetCounter(counterObject: Record<string, any>, defaultKey = '') {
return function getCounter(id = defaultKey) {
if (counterObject[id] === undefined) {
counterObject[id] = 0
}
return counterObject[id]++
}
}
interface Fetch {
(context: ComponentInstance): any | Promise<any>
}
interface UseFetchOptions {
expose?: string,
manual?: boolean,
}
const fetches = new WeakMap<ComponentInstance, Fetch[]>()
const fetchPromises = new Map<Fetch, Promise<any>>()
const isSsrHydration = (vm: ComponentInstance) =>
(vm.$vnode?.elm as any)?.dataset?.fetchKey
interface AugmentedComponentInstance extends ComponentInstance {
_fetchKey?: number | string
_data?: any
_hydrated?: boolean
_fetchDelay?: number
_fetchOnServer?: boolean
}
interface AugmentedNuxtApp extends NuxtApp {
isPreview?: boolean
_payloadFetchIndex?: number
_pagePayload?: any
}
function registerCallback(vm: ComponentInstance, callback: Fetch) {
const callbacks = fetches.get(vm) || []
fetches.set(vm, [...callbacks, callback])
}
async function callFetches(this: AugmentedComponentInstance) {
const fetchesToCall = fetches.get(this)
if (!fetchesToCall) return
;(this[globalNuxt] as any).nbFetching++
this.$fetchState.pending = true
this.$fetchState.error = null
this._hydrated = false
let error = null
const startTime = Date.now()
try {
await Promise.all(
fetchesToCall.map(fetch => {
if (fetchPromises.has(fetch)) return fetchPromises.get(fetch)
const promise = Promise.resolve(fetch(this)).finally(() =>
fetchPromises.delete(fetch)
)
fetchPromises.set(fetch, promise)
return promise
})
)
} catch (err) {
if ((process as any).dev) {
console.error('Error in fetch():', err)
}
error = normalizeError(err)
}
const delayLeft = (this._fetchDelay || 0) - (Date.now() - startTime)
if (delayLeft > 0) {
await new Promise(resolve => setTimeout(resolve, delayLeft))
}
this.$fetchState.error = error
this.$fetchState.pending = false
this.$fetchState.timestamp = Date.now()
this.$nextTick(() => (this[globalNuxt] as any).nbFetching--)
}
const setFetchState = (vm: AugmentedComponentInstance) => {
vm.$fetchState =
vm.$fetchState ||
reactive({
error: null,
pending: false,
timestamp: 0,
})
}
const loadFullStatic = (vm: AugmentedComponentInstance) => {
vm._fetchKey = getKey(vm)
// Check if component has been fetched on server
const { fetchOnServer } = vm.$options
const fetchedOnServer =
typeof fetchOnServer === 'function'
? fetchOnServer.call(vm) !== false
: fetchOnServer !== false
const nuxt = vm[globalNuxt] as AugmentedNuxtApp
if (!fetchedOnServer || nuxt?.isPreview || !nuxt?._pagePayload) {
return
}
vm._hydrated = true
const data = nuxt._pagePayload.fetch[vm._fetchKey!]
// If fetch error
if (data && data._error) {
vm.$fetchState.error = data._error
return
}
onBeforeMount(() => {
// Merge data
for (const key in data) {
set(vm, key, data[key])
}
})
}
async function serverPrefetch(vm: AugmentedComponentInstance) {
if (!vm._fetchOnServer) return
// Call and await on $fetch
setFetchState(vm)
try {
await callFetches.call(vm)
} catch (err) {
if ((process as any).dev) {
console.error('Error in fetch():', err)
}
vm.$fetchState.error = normalizeError(err)
}
vm.$fetchState.pending = false
// Define an ssrKey for hydration
vm._fetchKey =
// Nuxt 2.15+ uses a different format - an object rather than an array
'push' in vm.$ssrContext.nuxt.fetch
? vm.$ssrContext.nuxt.fetch.length
: vm._fetchKey || vm.$ssrContext.fetchCounters['']++
// Add data-fetch-key on parent element of Component
if (!vm.$vnode.data) vm.$vnode.data = {}
const attrs = (vm.$vnode.data.attrs = vm.$vnode.data.attrs || {})
attrs['data-fetch-key'] = vm._fetchKey
const data = { ...vm._data }
Object.entries((vm as any).__composition_api_state__.rawBindings).forEach(
([key, val]) => {
if (val instanceof Function || val instanceof Promise) return
data[key] = isRef(val) ? val.value : val
}
)
// Add to ssrContext for window.__NUXT__.fetch
const content = vm.$fetchState.error
? { _error: vm.$fetchState.error }
: JSON.parse(JSON.stringify(data))
if ('push' in vm.$ssrContext.nuxt.fetch) {
vm.$ssrContext.nuxt.fetch.push(content)
} else {
vm.$ssrContext.nuxt.fetch[vm._fetchKey!] = content
}
}
function getKey(vm: AugmentedComponentInstance) {
const nuxtState = vm[globalNuxt] as any
if (process.server && 'push' in vm.$ssrContext.nuxt.fetch) {
return undefined
} else if (process.client && '_payloadFetchIndex' in nuxtState) {
nuxtState._payloadFetchIndex = nuxtState._payloadFetchIndex || 0
return nuxtState._payloadFetchIndex++
}
const defaultKey = (vm.$options as any)._scopeId || vm.$options.name || ''
const getCounter = createGetCounter(
process.server
? vm.$ssrContext.fetchCounters
: (vm[globalNuxt] as any)._fetchCounters,
defaultKey
)
const options: {
fetchKey:
| ((getCounter: ReturnType<typeof createGetCounter>) => string)
| string
} = vm.$options as any
if (typeof options.fetchKey === 'function') {
return options.fetchKey.call(vm, getCounter)
} else {
const key =
'string' === typeof options.fetchKey ? options.fetchKey : defaultKey
return key ? key + ':' + getCounter(key) : String(getCounter(key))
}
}
/**
* Versions of Nuxt newer than v2.12 support a [custom hook called `fetch`](https://nuxtjs.org/api/pages-fetch/) that allows server-side and client-side asynchronous data-fetching.
* @param callback The async function you want to run.
* @example
```ts
import { defineComponent, ref, useFetch } from '@nuxtjs/composition-api'
import axios from 'axios'
export default defineComponent({
setup() {
const name = ref('')
const { fetch, fetchState } = useFetch(async () => {
name.value = await axios.get('https://myapi.com/name')
})
// Manually trigger a refetch
fetch()
// Access fetch error, pending and timestamp
fetchState
return { name }
},
})
```
```ts
import { defineComponent, ref, useFetch } from '@nuxtjs/composition-api'
import axios from 'axios'
export default defineComponent({
setup() {
const { fetch, fetchState, data } = useFetch(
async () => {
// The return value will be set to
return await axios.get('https://myapi.com/name')
},
{
manual: true, // Disable auto fetch unless `fetch()` is called manually
expose: 'name', // The name exposed to the template by which can access the hook's return value
},
)
// Manually trigger a refetch
fetch()
// Access the returned value of fetch hook
data.value
},
})
```
*/
export const useFetch = (callback: Fetch, options: UseFetchOptions) => {
const vm = getCurrentInstance() as AugmentedComponentInstance | undefined
if (!vm) throw new Error('This must be called within a setup function.')
const resultData = ref()
let callbackProxy: Fetch = async function (this: any, ...args) {
const result = await callback.apply(this, args)
resultData.value = result
return result
}
if (options.manual) {
let callbackManually:Fetch = () => {
callbackManually = callbackProxy
}
registerCallback(vm, callbackManually)
} else {
registerCallback(vm, callbackProxy)
}
if (options.expose) {
vm[options.expose] = resultData
}
if (typeof vm.$options.fetchOnServer === 'function') {
vm._fetchOnServer = vm.$options.fetchOnServer.call(vm) !== false
} else {
vm._fetchOnServer = vm.$options.fetchOnServer !== false
}
if (process.server) {
vm._fetchKey = getKey(vm)
}
setFetchState(vm)
onServerPrefetch(() => serverPrefetch(vm))
function result() {
return {
fetch: vm!.$fetch,
fetchState: vm!.$fetchState,
$fetch: vm!.$fetch,
$fetchState: vm!.$fetchState,
data: resultData,
}
}
vm._fetchDelay =
typeof vm.$options.fetchDelay === 'number' ? vm.$options.fetchDelay : 0
vm.$fetch = callFetches.bind(vm)
onBeforeMount(() => !vm._hydrated && callFetches.call(vm))
if (process.server || !isSsrHydration(vm)) {
if (process.client && isFullStatic) loadFullStatic(vm)
return result()
}
// Hydrate component
vm._hydrated = true
vm._fetchKey = (vm.$vnode.elm as any)?.dataset.fetchKey || getKey(vm)
const data = nuxtState.fetch[vm._fetchKey!]
// If fetch error
if (data && data._error) {
vm.$fetchState.error = data._error
return result()
}
onBeforeMount(() => {
// Merge data
for (const key in data) {
try {
if (key in vm && typeof vm[key as keyof typeof vm] === 'function') {
continue
}
set(vm, key, data[key])
} catch (e) {
if (process.env.NODE_ENV === 'development')
// eslint-disable-next-line
console.warn(`Could not hydrate ${key}.`)
}
}
})
return result()
}