This commit is contained in:
36
lib/mdx.ts
36
lib/mdx.ts
@@ -17,11 +17,38 @@ export type Post = {
|
||||
content: string;
|
||||
};
|
||||
|
||||
function readPostMetadata(data: Record<string, unknown>, slug: string): PostMetadata {
|
||||
if (
|
||||
typeof data.title !== 'string' ||
|
||||
typeof data.date !== 'string' ||
|
||||
typeof data.description !== 'string'
|
||||
) {
|
||||
throw new Error(`Invalid frontmatter for post: ${slug}`);
|
||||
}
|
||||
|
||||
if (!Number.isFinite(Date.parse(data.date))) {
|
||||
throw new Error(`Invalid date for post: ${slug}`);
|
||||
}
|
||||
|
||||
return {
|
||||
title: data.title,
|
||||
date: data.date,
|
||||
description: data.description,
|
||||
slug,
|
||||
tags: Array.isArray(data.tags)
|
||||
? data.tags.filter((tag): tag is string => typeof tag === 'string')
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function getPostSlugs() {
|
||||
if (!fs.existsSync(postsDirectory)) {
|
||||
return [];
|
||||
}
|
||||
return fs.readdirSync(postsDirectory);
|
||||
return fs
|
||||
.readdirSync(postsDirectory, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => entry.name);
|
||||
}
|
||||
|
||||
export function getPostBySlug(slug: string): Post {
|
||||
@@ -43,10 +70,7 @@ export function getPostBySlug(slug: string): Post {
|
||||
const { data, content } = matter(fileContents);
|
||||
|
||||
return {
|
||||
metadata: {
|
||||
...data,
|
||||
slug: realSlug,
|
||||
} as PostMetadata,
|
||||
metadata: readPostMetadata(data, realSlug),
|
||||
content,
|
||||
};
|
||||
}
|
||||
@@ -57,6 +81,6 @@ export function getAllPosts(): PostMetadata[] {
|
||||
.filter((slug) => slug.endsWith('.mdx'))
|
||||
.map((slug) => getPostBySlug(slug).metadata)
|
||||
// Sort posts by date in descending order
|
||||
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1));
|
||||
.sort((post1, post2) => new Date(post2.date).getTime() - new Date(post1.date).getTime());
|
||||
return posts;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user