Skip to content

Commit

Permalink
fix(schemaOrg): avoid rendering empty schema graph
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Nov 1, 2024
1 parent cd3c4ca commit 9bd0cd8
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/schema-org/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export function SchemaOrgUnheadPlugin(config: MetaInput, meta: () => Partial<Met
const { loadResolver } = await import('./resolver')
const nodes = await tag.props.nodes
for (const node of Array.isArray(nodes) ? nodes : [nodes]) {
// malformed input
if (typeof node !== 'object' || Object.keys(node).length === 0) {
continue
}
const newNode = {
...node,
_dedupeStrategy: tag.tagDuplicateStrategy,
Expand Down Expand Up @@ -78,12 +82,19 @@ export function SchemaOrgUnheadPlugin(config: MetaInput, meta: () => Partial<Met
},
'tags:resolve': async (ctx) => {
// find the schema.org node, should be a single instance
for (const tag of ctx.tags) {
for (const k in ctx.tags) {
const tag = ctx.tags[k]
if (tag.tag === 'script' && tag.props.type === 'application/ld+json' && tag.props.nodes) {
const resolvedGraph = graph.resolveGraph({ ...(await meta?.() || {}), ...config, ...resolvedMeta })
if (!resolvedGraph.length) {
// removes the tag
tag.props = {}
return
}
const minify = options?.minify || process.env.NODE_ENV === 'production'
tag.innerHTML = JSON.stringify({
'@context': 'https://schema.org',
'@graph': graph.resolveGraph({ ...(await meta?.() || {}), ...config, ...resolvedMeta }),
'@graph': resolvedGraph,
}, (_, value) => {
// process template params here
if (typeof value !== 'object')
Expand Down
3 changes: 3 additions & 0 deletions packages/schema-org/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,9 @@ export function useSchemaOrg(input: UseSchemaOrgInput, options?: Pick<HeadEntryO
const head = getActiveHead()
if (!head)
return
if ((Array.isArray(input) && input.length === 0) || !input) {
return
}
head.use(UnheadSchemaOrg())
return useHead<{ script: { nodes: UseSchemaOrgInput } }>({
script: [
Expand Down
17 changes: 17 additions & 0 deletions test/schema.org/e2e/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,4 +298,21 @@ describe('schema.org e2e', () => {
}</script>"
`)
})

it('empty', async () => {
const ssrHead = createHead({
plugins: [
SchemaOrgUnheadPlugin(),
],
})
useSchemaOrg(['test'])
useSchemaOrg([])
// @ts-expect-error intentional
useSchemaOrg('')
// @ts-expect-error intentional
useSchemaOrg('test')

const data = await renderSSRHead(ssrHead)
expect(data.bodyTags).toMatchInlineSnapshot(`""`)
})
})

0 comments on commit 9bd0cd8

Please sign in to comment.