2022-03-16 22:49:30 +00:00
|
|
|
import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch } from 'vue'
|
|
|
|
import type { Ref, WatchSource } from 'vue'
|
2021-08-27 13:30:53 +00:00
|
|
|
import { NuxtApp, useNuxtApp } from '#app'
|
2021-01-18 12:46:19 +00:00
|
|
|
|
2021-11-15 12:09:07 +00:00
|
|
|
export type _Transform<Input = any, Output = any> = (input: Input) => Output
|
2021-10-11 22:36:50 +00:00
|
|
|
|
2021-10-18 08:03:29 +00:00
|
|
|
export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? Pick<T, K[number]> : T
|
2021-10-12 08:52:09 +00:00
|
|
|
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
|
2021-10-11 22:36:50 +00:00
|
|
|
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
|
|
|
|
|
2022-03-16 22:49:30 +00:00
|
|
|
type MultiWatchSources = (WatchSource<unknown> | object)[];
|
|
|
|
|
2021-10-11 22:36:50 +00:00
|
|
|
export interface AsyncDataOptions<
|
|
|
|
DataT,
|
|
|
|
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
|
|
|
|
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
|
|
|
|
> {
|
2021-01-18 12:46:19 +00:00
|
|
|
server?: boolean
|
2021-11-15 12:09:07 +00:00
|
|
|
lazy?: boolean
|
2021-10-11 22:36:50 +00:00
|
|
|
default?: () => DataT
|
|
|
|
transform?: Transform
|
|
|
|
pick?: PickKeys
|
2022-03-16 22:49:30 +00:00
|
|
|
watch?: MultiWatchSources
|
2022-03-31 10:24:28 +00:00
|
|
|
initialCache?: boolean
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface RefreshOptions {
|
|
|
|
_initial?: boolean
|
2021-01-18 12:46:19 +00:00
|
|
|
}
|
|
|
|
|
2021-10-11 22:36:50 +00:00
|
|
|
export interface _AsyncData<DataT> {
|
|
|
|
data: Ref<DataT>
|
2021-02-03 18:14:30 +00:00
|
|
|
pending: Ref<boolean>
|
2022-03-31 10:24:28 +00:00
|
|
|
refresh: (opts?: RefreshOptions) => Promise<void>
|
2021-01-18 12:46:19 +00:00
|
|
|
error?: any
|
|
|
|
}
|
|
|
|
|
2021-10-11 22:36:50 +00:00
|
|
|
export type AsyncData<Data> = _AsyncData<Data> & Promise<_AsyncData<Data>>
|
2021-04-03 10:03:20 +00:00
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
const getDefault = () => null
|
2021-01-18 12:46:19 +00:00
|
|
|
|
2021-10-11 22:36:50 +00:00
|
|
|
export function useAsyncData<
|
|
|
|
DataT,
|
|
|
|
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
|
|
|
|
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
|
|
|
|
> (
|
|
|
|
key: string,
|
|
|
|
handler: (ctx?: NuxtApp) => Promise<DataT>,
|
|
|
|
options: AsyncDataOptions<DataT, Transform, PickKeys> = {}
|
2021-11-15 12:09:07 +00:00
|
|
|
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>> {
|
2021-10-08 14:21:55 +00:00
|
|
|
// Validate arguments
|
|
|
|
if (typeof key !== 'string') {
|
|
|
|
throw new TypeError('asyncData key must be a string')
|
|
|
|
}
|
|
|
|
if (typeof handler !== 'function') {
|
|
|
|
throw new TypeError('asyncData handler must be a function')
|
2021-01-18 12:46:19 +00:00
|
|
|
}
|
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
// Apply defaults
|
2021-11-15 12:09:07 +00:00
|
|
|
options = { server: true, default: getDefault, ...options }
|
|
|
|
// TODO: remove support for `defer` in Nuxt 3 RC
|
|
|
|
if ((options as any).defer) {
|
|
|
|
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
|
|
|
|
}
|
|
|
|
options.lazy = options.lazy ?? (options as any).defer ?? false
|
2022-03-31 10:24:28 +00:00
|
|
|
options.initialCache = options.initialCache ?? true
|
2021-04-03 10:03:20 +00:00
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
// Setup nuxt instance payload
|
|
|
|
const nuxt = useNuxtApp()
|
2021-01-18 12:46:19 +00:00
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
// Setup hook callbacks once per instance
|
|
|
|
const instance = getCurrentInstance()
|
2021-11-15 16:34:39 +00:00
|
|
|
if (instance && !instance._nuxtOnBeforeMountCbs) {
|
2021-10-08 14:21:55 +00:00
|
|
|
const cbs = instance._nuxtOnBeforeMountCbs = []
|
|
|
|
if (instance && process.client) {
|
|
|
|
onBeforeMount(() => {
|
|
|
|
cbs.forEach((cb) => { cb() })
|
|
|
|
cbs.splice(0, cbs.length)
|
|
|
|
})
|
|
|
|
onUnmounted(() => cbs.splice(0, cbs.length))
|
|
|
|
}
|
|
|
|
}
|
2021-03-17 09:17:18 +00:00
|
|
|
|
2022-04-05 11:51:07 +00:00
|
|
|
const useInitialCache = () => options.initialCache && nuxt.payload.data[key] !== undefined
|
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
const asyncData = {
|
|
|
|
data: ref(nuxt.payload.data[key] ?? options.default()),
|
2022-04-05 11:51:07 +00:00
|
|
|
pending: ref(!useInitialCache()),
|
2021-11-24 19:59:04 +00:00
|
|
|
error: ref(nuxt.payload._errors[key] ?? null)
|
2021-10-11 22:36:50 +00:00
|
|
|
} as AsyncData<DataT>
|
2021-03-17 09:17:18 +00:00
|
|
|
|
2022-03-31 10:24:28 +00:00
|
|
|
asyncData.refresh = (opts = {}) => {
|
2021-10-08 14:21:55 +00:00
|
|
|
// Avoid fetching same key more than once at a time
|
2022-03-31 10:24:28 +00:00
|
|
|
if (nuxt._asyncDataPromises[key]) {
|
2021-04-03 10:03:20 +00:00
|
|
|
return nuxt._asyncDataPromises[key]
|
2021-01-18 12:46:19 +00:00
|
|
|
}
|
2022-03-31 10:24:28 +00:00
|
|
|
// Avoid fetching same key that is already fetched
|
2022-04-05 11:51:07 +00:00
|
|
|
if (opts._initial && useInitialCache()) {
|
2022-03-31 10:24:28 +00:00
|
|
|
return nuxt.payload.data[key]
|
|
|
|
}
|
2021-10-08 14:21:55 +00:00
|
|
|
asyncData.pending.value = true
|
2021-11-24 19:59:04 +00:00
|
|
|
// TODO: Cancel previous promise
|
2021-10-08 14:21:55 +00:00
|
|
|
// TODO: Handle immediate errors
|
|
|
|
nuxt._asyncDataPromises[key] = Promise.resolve(handler(nuxt))
|
|
|
|
.then((result) => {
|
2021-10-11 22:36:50 +00:00
|
|
|
if (options.transform) {
|
|
|
|
result = options.transform(result)
|
|
|
|
}
|
|
|
|
if (options.pick) {
|
|
|
|
result = pick(result, options.pick) as DataT
|
|
|
|
}
|
2021-10-08 14:21:55 +00:00
|
|
|
asyncData.data.value = result
|
|
|
|
asyncData.error.value = null
|
|
|
|
})
|
|
|
|
.catch((error: any) => {
|
|
|
|
asyncData.error.value = error
|
|
|
|
asyncData.data.value = options.default()
|
|
|
|
})
|
|
|
|
.finally(() => {
|
|
|
|
asyncData.pending.value = false
|
|
|
|
nuxt.payload.data[key] = asyncData.data.value
|
2021-11-29 11:22:38 +00:00
|
|
|
if (asyncData.error.value) {
|
|
|
|
nuxt.payload._errors[key] = true
|
|
|
|
}
|
2021-10-08 14:21:55 +00:00
|
|
|
delete nuxt._asyncDataPromises[key]
|
|
|
|
})
|
|
|
|
return nuxt._asyncDataPromises[key]
|
|
|
|
}
|
2021-01-18 12:46:19 +00:00
|
|
|
|
2022-03-31 10:24:28 +00:00
|
|
|
const initialFetch = () => asyncData.refresh({ _initial: true })
|
|
|
|
|
2021-10-25 10:36:38 +00:00
|
|
|
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
|
2021-01-18 12:46:19 +00:00
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
// Server side
|
|
|
|
if (process.server && fetchOnServer) {
|
2022-03-31 10:24:28 +00:00
|
|
|
const promise = initialFetch()
|
2021-11-15 12:09:07 +00:00
|
|
|
onServerPrefetch(() => promise)
|
2021-10-08 14:21:55 +00:00
|
|
|
}
|
2021-04-03 10:03:20 +00:00
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
// Client side
|
|
|
|
if (process.client) {
|
2021-11-24 19:59:04 +00:00
|
|
|
if (fetchOnServer && nuxt.isHydrating) {
|
|
|
|
// 1. Hydration (server: true): no fetch
|
2021-10-08 14:21:55 +00:00
|
|
|
asyncData.pending.value = false
|
2021-11-24 19:59:04 +00:00
|
|
|
} else if (instance && (nuxt.isHydrating || options.lazy)) {
|
|
|
|
// 2. Initial load (server: false): fetch on mounted
|
|
|
|
// 3. Navigation (lazy: true): fetch on mounted
|
2022-03-31 10:24:28 +00:00
|
|
|
instance._nuxtOnBeforeMountCbs.push(initialFetch)
|
2021-11-24 19:59:04 +00:00
|
|
|
} else {
|
|
|
|
// 4. Navigation (lazy: false) - or plugin usage: await fetch
|
2022-03-31 10:24:28 +00:00
|
|
|
initialFetch()
|
2021-01-18 12:46:19 +00:00
|
|
|
}
|
2022-03-16 22:49:30 +00:00
|
|
|
if (options.watch) {
|
2022-03-28 17:12:41 +00:00
|
|
|
watch(options.watch, () => asyncData.refresh())
|
|
|
|
}
|
|
|
|
const off = nuxt.hook('app:data:refresh', (keys) => {
|
|
|
|
if (!keys || keys.includes(key)) {
|
|
|
|
return asyncData.refresh()
|
2022-03-16 22:49:30 +00:00
|
|
|
}
|
2022-03-28 17:12:41 +00:00
|
|
|
})
|
|
|
|
if (instance) {
|
|
|
|
onUnmounted(off)
|
2022-03-16 22:49:30 +00:00
|
|
|
}
|
2021-01-18 12:46:19 +00:00
|
|
|
}
|
2021-03-01 09:45:37 +00:00
|
|
|
|
2021-10-08 14:21:55 +00:00
|
|
|
// Allow directly awaiting on asyncData
|
2021-10-11 22:36:50 +00:00
|
|
|
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT>
|
2021-10-08 14:21:55 +00:00
|
|
|
Object.assign(asyncDataPromise, asyncData)
|
|
|
|
|
2022-04-04 10:56:41 +00:00
|
|
|
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>>
|
2021-10-11 22:36:50 +00:00
|
|
|
}
|
|
|
|
|
2021-11-15 12:09:07 +00:00
|
|
|
export function useLazyAsyncData<
|
|
|
|
DataT,
|
|
|
|
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
|
|
|
|
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
|
|
|
|
> (
|
|
|
|
key: string,
|
|
|
|
handler: (ctx?: NuxtApp) => Promise<DataT>,
|
|
|
|
options: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'> = {}
|
|
|
|
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>> {
|
|
|
|
return useAsyncData(key, handler, { ...options, lazy: true })
|
|
|
|
}
|
|
|
|
|
2022-03-28 17:12:41 +00:00
|
|
|
export function refreshNuxtData (keys?: string | string[]): Promise<void> {
|
|
|
|
if (process.server) {
|
|
|
|
return Promise.resolve()
|
|
|
|
}
|
|
|
|
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
|
|
|
|
return useNuxtApp().callHook('app:data:refresh', _keys)
|
|
|
|
}
|
|
|
|
|
2021-10-11 22:36:50 +00:00
|
|
|
function pick (obj: Record<string, any>, keys: string[]) {
|
|
|
|
const newObj = {}
|
|
|
|
for (const key of keys) {
|
|
|
|
newObj[key] = obj[key]
|
|
|
|
}
|
|
|
|
return newObj
|
2021-03-01 09:45:37 +00:00
|
|
|
}
|