almost done
This commit is contained in:
86
lib/blog.ts
Normal file
86
lib/blog.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
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`);
|
||||
let 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) {
|
||||
let mdxFiles = getMDXFiles(dir);
|
||||
console.log(dir);
|
||||
console.log(category);
|
||||
console.log(mdxFiles);
|
||||
const posts = await Promise.all(
|
||||
mdxFiles.map(async (file) => {
|
||||
let slug = path.basename(file, path.extname(file));
|
||||
let { 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 getBlogPosts(category?: string) {
|
||||
let postPath = path.join(process.cwd(), "content");
|
||||
console.log(postPath);
|
||||
return getAllPosts(postPath, category);
|
||||
}
|
||||
Reference in New Issue
Block a user