86 lines
2.1 KiB
TypeScript
86 lines
2.1 KiB
TypeScript
import fs from "fs";
|
|
import matter from "gray-matter";
|
|
import path from "path";
|
|
import rehypePrettyCode from "rehype-pretty-code";
|
|
import rehypeStringify from "rehype-stringify";
|
|
import remarkGfm from "remark-gfm";
|
|
import remarkParse from "remark-parse";
|
|
import remarkRehype from "remark-rehype";
|
|
import { unified } from "unified";
|
|
|
|
type Metadata = {
|
|
title: string;
|
|
publishedAt: string;
|
|
summary: string;
|
|
image?: string;
|
|
category?: string;
|
|
};
|
|
|
|
function getMDXFiles(dir: string) {
|
|
return fs.readdirSync(dir).filter((file) => path.extname(file) === ".mdx");
|
|
}
|
|
|
|
export async function markdownToHTML(markdown: string) {
|
|
const p = await unified()
|
|
.use(remarkParse)
|
|
.use(remarkGfm)
|
|
.use(remarkRehype)
|
|
.use(rehypePrettyCode, {
|
|
theme: {
|
|
light: "min-light",
|
|
dark: "min-dark",
|
|
},
|
|
keepBackground: false,
|
|
})
|
|
.use(rehypeStringify)
|
|
.process(markdown);
|
|
|
|
return p.toString();
|
|
}
|
|
|
|
export async function getPost(slug: string) {
|
|
const filePath = path.join("content", `${slug}.mdx`);
|
|
const source = fs.readFileSync(filePath, "utf-8");
|
|
const { content: rawContent, data: metadata } = matter(source);
|
|
const content = await markdownToHTML(rawContent);
|
|
return {
|
|
source: content,
|
|
metadata: metadata as Metadata,
|
|
slug,
|
|
};
|
|
}
|
|
|
|
async function getAllPosts(dir: string, category?: string) {
|
|
const mdxFiles = getMDXFiles(dir);
|
|
console.log(dir);
|
|
console.log(category);
|
|
console.log(mdxFiles);
|
|
const posts = await Promise.all(
|
|
mdxFiles.map(async (file) => {
|
|
const slug = path.basename(file, path.extname(file));
|
|
const { metadata, source } = await getPost(slug);
|
|
console.log(file);
|
|
console.log(slug);
|
|
console.log(metadata);
|
|
console.log(source);
|
|
|
|
return {
|
|
metadata,
|
|
slug,
|
|
source,
|
|
};
|
|
})
|
|
);
|
|
|
|
if (category) {
|
|
return posts.filter((post) => post.metadata.category === category);
|
|
}
|
|
console.log(posts);
|
|
return posts;
|
|
}
|
|
|
|
export async function getPosts(category?: string) {
|
|
const postPath = path.join(process.cwd(), "content");
|
|
console.log(postPath);
|
|
return getAllPosts(postPath, category);
|
|
} |