feat(nuxt): allow customising defaults for data composables (#23725)

This commit is contained in:
Daniel Roe 2023-10-18 15:25:25 +01:00 committed by GitHub
parent 9dd304628a
commit 5652346d7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 31 additions and 2 deletions

View File

@ -5,6 +5,9 @@ import { useNuxtApp } from '../nuxt'
import { createError } from './error' import { createError } from './error'
import { onNuxtReady } from './ready' import { onNuxtReady } from './ready'
// @ts-expect-error virtual file
import { asyncDataDefaults } from '#build/nuxt.config.mjs'
export type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error' export type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'
export type _Transform<Input = any, Output = any> = (input: Input) => Output export type _Transform<Input = any, Output = any> = (input: Input) => Output
@ -146,6 +149,7 @@ export function useAsyncData<
options.lazy = options.lazy ?? false options.lazy = options.lazy ?? false
options.immediate = options.immediate ?? true options.immediate = options.immediate ?? true
options.deep = options.deep ?? asyncDataDefaults.deep
const hasCachedData = () => ![null, undefined].includes(options.getCachedData!(key) as any) const hasCachedData = () => ![null, undefined].includes(options.getCachedData!(key) as any)
@ -153,7 +157,7 @@ export function useAsyncData<
if (!nuxt._asyncData[key] || !options.immediate) { if (!nuxt._asyncData[key] || !options.immediate) {
nuxt.payload._errors[key] ??= null nuxt.payload._errors[key] ??= null
const _ref = options.deep !== true ? shallowRef : ref const _ref = options.deep ? ref : shallowRef
nuxt._asyncData[key] = { nuxt._asyncData[key] = {
data: _ref(options.getCachedData!(key) ?? options.default!()), data: _ref(options.getCachedData!(key) ?? options.default!()),

View File

@ -3,10 +3,14 @@ import type { NitroFetchRequest, TypedInternalResponse, AvailableRouterMethod as
import type { MaybeRef, Ref } from 'vue' import type { MaybeRef, Ref } from 'vue'
import { computed, reactive, unref } from 'vue' import { computed, reactive, unref } from 'vue'
import { hash } from 'ohash' import { hash } from 'ohash'
import { useRequestFetch } from './ssr' import { useRequestFetch } from './ssr'
import type { AsyncData, AsyncDataOptions, KeysOf, MultiWatchSources, PickFrom } from './asyncData' import type { AsyncData, AsyncDataOptions, KeysOf, MultiWatchSources, PickFrom } from './asyncData'
import { useAsyncData } from './asyncData' import { useAsyncData } from './asyncData'
// @ts-expect-error virtual file
import { fetchDefaults } from '#build/nuxt.config.mjs'
// support uppercase methods, detail: https://github.com/nuxt/nuxt/issues/22313 // support uppercase methods, detail: https://github.com/nuxt/nuxt/issues/22313
type AvailableRouterMethod<R extends NitroFetchRequest> = _AvailableRouterMethod<R> | Uppercase<_AvailableRouterMethod<R>> type AvailableRouterMethod<R extends NitroFetchRequest> = _AvailableRouterMethod<R> | Uppercase<_AvailableRouterMethod<R>>
@ -113,6 +117,7 @@ export function useFetch<
} = opts } = opts
const _fetchOptions = reactive({ const _fetchOptions = reactive({
...fetchDefaults,
...fetchOptions, ...fetchOptions,
cache: typeof opts.cache === 'boolean' ? undefined : opts.cache cache: typeof opts.cache === 'boolean' ? undefined : opts.cache
}) })

View File

@ -338,6 +338,11 @@ export const publicPathTemplate: NuxtTemplate = {
export const nuxtConfigTemplate = { export const nuxtConfigTemplate = {
filename: 'nuxt.config.mjs', filename: 'nuxt.config.mjs',
getContents: (ctx: TemplateContext) => { getContents: (ctx: TemplateContext) => {
const fetchDefaults = {
...ctx.nuxt.options.experimental.defaults.useFetch,
baseURL: undefined,
headers: undefined
}
return [ return [
...Object.entries(ctx.nuxt.options.app).map(([k, v]) => `export const ${camelCase('app-' + k)} = ${JSON.stringify(v)}`), ...Object.entries(ctx.nuxt.options.app).map(([k, v]) => `export const ${camelCase('app-' + k)} = ${JSON.stringify(v)}`),
`export const renderJsonPayloads = ${!!ctx.nuxt.options.experimental.renderJsonPayloads}`, `export const renderJsonPayloads = ${!!ctx.nuxt.options.experimental.renderJsonPayloads}`,
@ -348,6 +353,8 @@ export const nuxtConfigTemplate = {
`export const devPagesDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.dir.pages) : 'null'}`, `export const devPagesDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.dir.pages) : 'null'}`,
`export const devRootDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.rootDir) : 'null'}`, `export const devRootDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.rootDir) : 'null'}`,
`export const nuxtLinkDefaults = ${JSON.stringify(ctx.nuxt.options.experimental.defaults.nuxtLink)}`, `export const nuxtLinkDefaults = ${JSON.stringify(ctx.nuxt.options.experimental.defaults.nuxtLink)}`,
`export const asyncDataDefaults = ${JSON.stringify(ctx.nuxt.options.experimental.defaults.useAsyncData)}`,
`export const fetchDefaults = ${JSON.stringify(fetchDefaults)}`,
`export const vueAppRootContainer = ${ctx.nuxt.options.app.rootId ? `'#${ctx.nuxt.options.app.rootId}'` : `'body > ${ctx.nuxt.options.app.rootTag}'`}` `export const vueAppRootContainer = ${ctx.nuxt.options.app.rootId ? `'#${ctx.nuxt.options.app.rootId}'` : `'body > ${ctx.nuxt.options.app.rootTag}'`}`
].join('\n\n') ].join('\n\n')
} }

View File

@ -21,6 +21,7 @@ export default defineBuildConfig({
externals: [ externals: [
// Type imports // Type imports
'#app/components/nuxt-link', '#app/components/nuxt-link',
'ofetch',
'vue-router', 'vue-router',
'@nuxt/telemetry', '@nuxt/telemetry',
'vue-bundle-renderer', 'vue-bundle-renderer',

View File

@ -41,6 +41,7 @@
"h3": "1.8.2", "h3": "1.8.2",
"ignore": "5.2.4", "ignore": "5.2.4",
"nitropack": "2.6.3", "nitropack": "2.6.3",
"ofetch": "^1.3.3",
"unbuild": "latest", "unbuild": "latest",
"unctx": "2.3.1", "unctx": "2.3.1",
"vite": "4.5.0", "vite": "4.5.0",

View File

@ -258,7 +258,15 @@ export default defineUntypedSchema({
/** @type {typeof import('#app/components/nuxt-link')['NuxtLinkOptions']} */ /** @type {typeof import('#app/components/nuxt-link')['NuxtLinkOptions']} */
nuxtLink: { nuxtLink: {
componentName: 'NuxtLink' componentName: 'NuxtLink'
} },
/**
* Options that apply to `useAsyncData` (and also therefore `useFetch`)
*/
useAsyncData: {
deep: true
},
/** @type {Pick<typeof import('ofetch')['FetchOptions'], 'timeout' | 'retry' | 'retryDelay' | 'retryStatusCodes'>} */
useFetch: {}
} }
} }
}) })

View File

@ -490,6 +490,9 @@ importers:
nitropack: nitropack:
specifier: 2.6.3 specifier: 2.6.3
version: 2.6.3 version: 2.6.3
ofetch:
specifier: ^1.3.3
version: 1.3.3
unbuild: unbuild:
specifier: latest specifier: latest
version: 2.0.0(typescript@5.2.2) version: 2.0.0(typescript@5.2.2)