48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import matter from "gray-matter";
|
|
import { join } from "path";
|
|
import fs from "fs";
|
|
import { FrontMatter, MarkdownDocument } from "../types/types";
|
|
import { remark } from "remark";
|
|
import html from "remark-html";
|
|
|
|
export const BLOGS_PATH = join(process.cwd(), "content/blogs");
|
|
|
|
export const getFileContentBySlug = (slug: string): MarkdownDocument => {
|
|
const filepath = join(BLOGS_PATH, `${slug}.md` || `${slug}.mdx`);
|
|
const filecontents = fs.readFileSync(filepath);
|
|
|
|
const { data, content } = matter(filecontents);
|
|
|
|
return {
|
|
frontMatter: data,
|
|
content: content,
|
|
};
|
|
};
|
|
|
|
export interface BlogPost {
|
|
frontMatter: FrontMatter;
|
|
slug: string;
|
|
}
|
|
|
|
export const getAllFilesFrontMatter = (): BlogPost[] => {
|
|
const files = fs.readdirSync(BLOGS_PATH);
|
|
|
|
return files.reduce((allPosts: BlogPost[], postSlug: string) => {
|
|
const slug = postSlug.replace(".md", "");
|
|
const post = getFileContentBySlug(slug);
|
|
|
|
return [{ frontMatter: post.frontMatter, slug }, ...allPosts];
|
|
}, []);
|
|
};
|
|
|
|
export async function markdownToHtml(markdown: any) {
|
|
const result = await remark().use(html).process(markdown);
|
|
return result.toString();
|
|
}
|
|
|
|
export const renderMarkdown = async (
|
|
markdownContent: string
|
|
): Promise<string> => {
|
|
return await markdownToHtml(markdownContent || "");
|
|
};
|