Skip to content

Commit

Permalink
fix(meta): strip null values from unpackMeta
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Dec 23, 2022
1 parent 5df1205 commit 4b5c734
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
6 changes: 5 additions & 1 deletion packages/schema/src/metaFlat.ts
Expand Up @@ -622,6 +622,10 @@ export interface MetaFlat {
}
}

export type MetaFlatInput = Partial<MetaFlat>
// make MetaFlat record entries also possibly be null
type MetaFlatNullable = {
[K in keyof MetaFlat]: MetaFlat[K] | null
}
export type MetaFlatInput = Partial<MetaFlatNullable>

export type AsyncMetaFlatInput = MaybePromiseProps<MetaFlatInput>
9 changes: 8 additions & 1 deletion packages/zhead/src/meta/unpack.ts
Expand Up @@ -8,7 +8,7 @@ import { MetaPackingSchema, resolveMetaKeyType } from './utils'
* @param input
*/
export function unpackMeta<T extends MetaFlatInput>(input: T): Required<Head>['meta'] {
return unpackToArray((input), {
const meta = unpackToArray((input), {
key({ key }) {
return resolveMetaKeyType(key) as string
},
Expand All @@ -19,6 +19,9 @@ export function unpackMeta<T extends MetaFlatInput>(input: T): Required<Head>['m
return MetaPackingSchema[key]?.keyValue || fixKeyCase(key)
},
resolveValueData({ value, key }) {
if (value === null) {
return '_null'
}
if (typeof value === 'object') {
const definition = MetaPackingSchema[key]

Expand All @@ -31,6 +34,8 @@ export function unpackMeta<T extends MetaFlatInput>(input: T): Required<Head>['m
entrySeparator: ', ',
keyValueSeparator: '=',
resolve({ value, key }) {
if (value === null)
return ''
if (typeof value === 'boolean')
return `${key}`
},
Expand All @@ -41,4 +46,6 @@ export function unpackMeta<T extends MetaFlatInput>(input: T): Required<Head>['m
return typeof value === 'number' ? value.toString() : value
},
})
// remove keys with defined but empty content
return meta.filter(v => typeof v.content === 'undefined' || v.content !== '_null')
}
16 changes: 16 additions & 0 deletions test/zhead/unpackMeta.ts → test/zhead/unpackMeta.test.ts
Expand Up @@ -2,6 +2,22 @@ import { describe, it } from 'vitest'
import { packMeta, unpackMeta } from 'zhead'

describe('unpackMeta', () => {
it('null values', () => {
const tags = unpackMeta({
ogTitle: 'should stay',
description: null
})

expect(tags).toMatchInlineSnapshot(`
[
{
"content": "should stay",
"property": "og:title",
},
]
`)
})

it('charset', () => {
const tags = unpackMeta({
charset: 'utf-8',
Expand Down

0 comments on commit 4b5c734

Please sign in to comment.