Unverified Commit ede8d1b8 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[metadata] refactor metadata sitemap loader code (#83443)

parent 684c7c01
...@@ -25,7 +25,10 @@ async function createReExportsCode( ...@@ -25,7 +25,10 @@ async function createReExportsCode(
) )
// Re-export configs but avoid conflicted exports // Re-export configs but avoid conflicted exports
const reExportNames = exportNames.filter( const reExportNames = exportNames.filter(
(name) => name !== 'default' && name !== 'generateSitemaps' (name) =>
name !== 'default' &&
name !== 'generateSitemaps' &&
name !== 'dynamicParams'
) )
return reExportNames.length > 0 return reExportNames.length > 0
...@@ -157,22 +160,6 @@ async function getDynamicImageRouteCode( ...@@ -157,22 +160,6 @@ async function getDynamicImageRouteCode(
resourcePath: string, resourcePath: string,
loaderContext: webpack.LoaderContext<any> loaderContext: webpack.LoaderContext<any>
) { ) {
let staticGenerationCode = ''
if (process.env.NODE_ENV === 'production') {
staticGenerationCode = `\
export async function generateStaticParams({ params }) {
const imageMetadata = await generateImageMetadata({ params })
const staticParams = []
for (const item of imageMetadata) {
staticParams.push({ __metadata_id__: item.id.toString() })
}
return staticParams
}
`
}
return `\ return `\
/* dynamic image route with generateImageMetadata */ /* dynamic image route with generateImageMetadata */
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
...@@ -185,25 +172,41 @@ export async function GET(_, ctx) { ...@@ -185,25 +172,41 @@ export async function GET(_, ctx) {
const params = await ctx.params const params = await ctx.params
const { __metadata_id__, ...rest } = params || {} const { __metadata_id__, ...rest } = params || {}
const restParams = params ? rest : undefined const restParams = params ? rest : undefined
const imageMetadata = await generateImageMetadata({ params: restParams })
const id = imageMetadata.find((item) => { ${/* we need a dev assertion for id since dynamicParams=false won't work well in dev */ ''}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const imageMetadata = await generateImageMetadata({ params: restParams })
const id = imageMetadata.find((item) => {
if (item?.id == null) { if (item?.id == null) {
throw new Error('id property is required for every item returned from generateImageMetadata') throw new Error('id property is required for every item returned from generateImageMetadata')
} }
return item.id.toString() === __metadata_id__
})?.id
if (id == null) {
return new NextResponse('Not Found', {
status: 404,
})
} }
return item.id.toString() === __metadata_id__
})?.id
if (id == null) {
return new NextResponse('Not Found', {
status: 404,
})
} }
return handler({ params: restParams, id }) return handler({ params: restParams, id: __metadata_id__ })
} }
${staticGenerationCode} export const dynamicParams = false
export async function generateStaticParams({ params }) {
const imageMetadata = await generateImageMetadata({ params })
const staticParams = []
for (const item of imageMetadata) {
if (item?.id == null) {
throw new Error('id property is required for every item returned from generateImageMetadata')
}
staticParams.push({ __metadata_id__: item.id.toString() })
}
return staticParams
}
` `
} }
...@@ -244,41 +247,46 @@ async function getImageRouteCode( ...@@ -244,41 +247,46 @@ async function getImageRouteCode(
} }
} }
async function getDynamicSitemapRouteCode( async function getSingleSitemapRouteCode(
resourcePath: string, resourcePath: string,
loaderContext: webpack.LoaderContext<any> loaderContext: webpack.LoaderContext<any>
) { ) {
let staticGenerationCode = '' return `\
/* single sitemap route */
import { NextResponse } from 'next/server'
import { default as handler } from ${JSON.stringify(resourcePath)}
import { resolveRouteData } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data'
const exportNames = await getLoaderModuleNamedExports( const contentType = ${JSON.stringify(getContentType(resourcePath))}
resourcePath, const fileType = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)}
loaderContext
)
const hasGenerateSitemaps = exportNames.includes('generateSitemaps') ${errorOnBadHandler(resourcePath)}
${await createReExportsCode(resourcePath, loaderContext)}
if (process.env.NODE_ENV === 'production' && hasGenerateSitemaps) { export async function GET() {
staticGenerationCode = `\ const data = await handler()
/* dynamic sitemap route */ const content = resolveRouteData(data, fileType)
export async function generateStaticParams() {
const sitemaps = await sitemapModule.generateSitemaps()
const params = []
for (const item of sitemaps) { return new NextResponse(content, {
params.push({ __metadata_id__: item.id.toString() + '.xml' }) headers: {
} 'Content-Type': contentType,
return params 'Cache-Control': ${JSON.stringify(CACHE_HEADERS.REVALIDATE)},
} },
` })
} }
`
}
async function getDynamicSitemapRouteCode(
resourcePath: string,
loaderContext: webpack.LoaderContext<any>
) {
const code = `\ const code = `\
/* dynamic sitemap route with generateSitemaps */
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import * as userland from ${JSON.stringify(resourcePath)} import { default as handler, generateSitemaps } from ${JSON.stringify(resourcePath)}
import { resolveRouteData } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data' import { resolveRouteData } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data'
const sitemapModule = { ...userland }
const handler = sitemapModule.default
const contentType = ${JSON.stringify(getContentType(resourcePath))} const contentType = ${JSON.stringify(getContentType(resourcePath))}
const fileType = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)} const fileType = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)}
...@@ -288,18 +296,24 @@ ${await createReExportsCode(resourcePath, loaderContext)} ...@@ -288,18 +296,24 @@ ${await createReExportsCode(resourcePath, loaderContext)}
export async function GET(_, ctx) { export async function GET(_, ctx) {
const { __metadata_id__: id, ...params } = await ctx.params || {} const { __metadata_id__: id, ...params } = await ctx.params || {}
const hasXmlExtension = id ? id.endsWith('.xml') : false const hasXmlExtension = id ? id.endsWith('.xml') : false
if (id && !hasXmlExtension) {
return new NextResponse('Not Found', {
status: 404,
})
}
if (process.env.NODE_ENV !== 'production' && sitemapModule.generateSitemaps) { if (process.env.NODE_ENV !== 'production') {
const sitemaps = await sitemapModule.generateSitemaps() const sitemaps = await generateSitemaps()
let foundId
for (const item of sitemaps) { for (const item of sitemaps) {
if (item?.id == null) { if (item?.id == null) {
throw new Error('id property is required for every item returned from generateSitemaps') throw new Error('id property is required for every item returned from generateSitemaps')
} }
const baseId = id && hasXmlExtension ? id.slice(0, -4) : undefined
if (item.id.toString() === baseId) {
foundId = item.id
}
}
if (foundId == null) {
return new NextResponse('Not Found', {
status: 404,
})
} }
} }
...@@ -315,11 +329,42 @@ export async function GET(_, ctx) { ...@@ -315,11 +329,42 @@ export async function GET(_, ctx) {
}) })
} }
${staticGenerationCode} export const dynamicParams = false
export async function generateStaticParams() {
const sitemaps = await generateSitemaps()
const params = []
for (const item of sitemaps) {
if (item?.id == null) {
throw new Error('id property is required for every item returned from generateSitemaps')
}
params.push({ __metadata_id__: item.id.toString() + '.xml' })
}
return params
}
` `
return code return code
} }
// <metadata-sitemap>/[id]/route.js
async function getSitemapRouteCode(
resourcePath: string,
loaderContext: webpack.LoaderContext<any>
) {
const exportNames = await getLoaderModuleNamedExports(
resourcePath,
loaderContext
)
const hasGenerateSitemaps = exportNames.includes('generateSitemaps')
if (hasGenerateSitemaps) {
return getDynamicSitemapRouteCode(resourcePath, loaderContext)
} else {
return getSingleSitemapRouteCode(resourcePath, loaderContext)
}
}
// When it's static route, it could be favicon.ico, sitemap.xml, robots.txt etc. // When it's static route, it could be favicon.ico, sitemap.xml, robots.txt etc.
// TODO-METADATA: improve the cache control strategy // TODO-METADATA: improve the cache control strategy
const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLoaderOptions> = const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLoaderOptions> =
...@@ -333,7 +378,7 @@ const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLo ...@@ -333,7 +378,7 @@ const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLo
if (fileBaseName === 'robots' || fileBaseName === 'manifest') { if (fileBaseName === 'robots' || fileBaseName === 'manifest') {
code = await getDynamicTextRouteCode(filePath, this) code = await getDynamicTextRouteCode(filePath, this)
} else if (fileBaseName === 'sitemap') { } else if (fileBaseName === 'sitemap') {
code = await getDynamicSitemapRouteCode(filePath, this) code = await getSitemapRouteCode(filePath, this)
} else { } else {
code = await getImageRouteCode(filePath, this) code = await getImageRouteCode(filePath, this)
} }
......
...@@ -86,6 +86,11 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -86,6 +86,11 @@ describe('app dir - metadata dynamic routes', () => {
} }
}) })
it('should 404 for non-existing id from generateImageMetadata', async () => {
const res = await next.fetch('/gsp/icon/non-existing-id')
expect(res.status).toBe(404)
})
it('should not throw if client components are imported but not used in sitemap', async () => { it('should not throw if client components are imported but not used in sitemap', async () => {
const { status } = await next.fetch('/client-ref-dependency/sitemap.xml') const { status } = await next.fetch('/client-ref-dependency/sitemap.xml')
expect(status).toBe(200) expect(status).toBe(200)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment