Skip to content

Commit

Permalink
handle null and undefined for front matter types
Browse files Browse the repository at this point in the history
  • Loading branch information
souporserious committed May 8, 2024
1 parent 2466741 commit 6d338a6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/tough-goats-hang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mdxts": patch
---

Handles null values and throws an error for undefined values when formatting front matter for type checking.
27 changes: 20 additions & 7 deletions packages/mdxts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,10 +206,17 @@ export function createSource<
const allModuleData = Object.values(allFilteredData)
let contents = `type frontMatter = ${frontMatterType};\n`

allModuleData.forEach((post) => {
const entries = Object.entries(post.frontMatter).map(([key, value]) => {
return `${key}: ${formatFrontMatterValue(value)}`
})
allModuleData.forEach((dataItem) => {
const entries = Object.entries(dataItem.frontMatter).map(
([key, value]) => {
if (value === undefined) {
throw new Error(
`Front matter key "${key}" is missing a value in "${dataItem.mdxPath}"`
)
}
return `${key}: ${formatFrontMatterValue(value)}`
}
)
contents += `({${entries.join(', ')}}) satisfies frontMatter;\n`
})

Expand Down Expand Up @@ -592,13 +599,19 @@ export function mergeSources<

/** Formats a value for front matter. */
function formatFrontMatterValue(value: any): string {
if (value === null) {
return 'null'
}
if (value instanceof Date) {
return `new Date('${value}')`
} else if (typeof value === 'boolean' || typeof value === 'number') {
}
if (typeof value === 'boolean' || typeof value === 'number') {
return `${value}`
} else if (Array.isArray(value)) {
}
if (Array.isArray(value)) {
return `[${value.map((item) => formatFrontMatterValue(item)).join(', ')}]`
} else if (typeof value === 'object') {
}
if (typeof value === 'object') {
return `{${Object.entries(value)
.map(([subKey, subValue]) => {
return `${subKey}: ${formatFrontMatterValue(subValue)}`
Expand Down

0 comments on commit 6d338a6

Please sign in to comment.