void/utils/shared/posts.ts
2022-08-10 00:35:26 +02:00

46 lines
1.1 KiB
TypeScript

import { remark } from "remark";
import html from "remark-html";
import fs from "fs";
import path from "path";
import matter from "gray-matter";
export async function getPostData(slug) {
const fullPath = path.join("posts", `${slug}.mdx`);
const fileContents = fs.readFileSync(fullPath, "utf8");
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents);
// Use remark to convert markdown into HTML string
const processedContent = await remark()
.use(html)
.process(matterResult.content);
const contentHtml = processedContent.toString();
// Combine the data with the id and contentHtml
return {
slug,
content: contentHtml,
...matterResult.data,
};
}
export async function getSortedPosts() {
const allPosts = getAllPostIDs()
let Posts = []
for (const Post of allPosts) {
Posts.push(await getPostData(Post.params.slug))
}
return Posts
}
export function getAllPostIDs() {
const n = fs.readdirSync("posts/");
return n.map((f) => {
return {
params: {
slug: f.replace(/\.mdx$/, ""),
},
};
});
}