70 lines
2.0 KiB
TypeScript
70 lines
2.0 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";
|
|
import remarkGfm from "remark-gfm";
|
|
|
|
export const BLOGS_PATH = join(process.cwd(), "content/blogs");
|
|
export const PROJECTS_PATH = join(process.cwd(), "content/projects");
|
|
export interface Post {
|
|
frontMatter: FrontMatter;
|
|
slug: string;
|
|
}
|
|
|
|
export const getBlogContentBySlug = (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 const getProjectContentBySlug = (slug: string): MarkdownDocument => {
|
|
const filepath = join(PROJECTS_PATH, `${slug}.md` || `${slug}.mdx`);
|
|
const filecontents = fs.readFileSync(filepath);
|
|
|
|
const { data, content } = matter(filecontents);
|
|
|
|
return {
|
|
frontMatter: data,
|
|
content: content,
|
|
};
|
|
};
|
|
|
|
export const getAllBlogsFrontMatter = (): Post[] => {
|
|
const files = fs.readdirSync(BLOGS_PATH);
|
|
|
|
return files.reduce((allPosts: Post[], postSlug: string) => {
|
|
const slug = postSlug.replace(".md", "");
|
|
const post = getBlogContentBySlug(slug);
|
|
|
|
return [{ frontMatter: post.frontMatter, slug }, ...allPosts];
|
|
}, []);
|
|
};
|
|
export const getAllProjectsFrontMatter = (): Post[] => {
|
|
const files = fs.readdirSync(PROJECTS_PATH);
|
|
|
|
return files.reduce((allPosts: Post[], postSlug: string) => {
|
|
const slug = postSlug.replace(".md", "");
|
|
const post = getProjectContentBySlug(slug);
|
|
|
|
return [{ frontMatter: post.frontMatter, slug }, ...allPosts];
|
|
}, []);
|
|
};
|
|
|
|
export async function markdownToHtml(markdown: any) {
|
|
const result = await remark().use(html).use(remarkGfm).process(markdown);
|
|
return result.toString();
|
|
}
|
|
|
|
export const renderMarkdown = async (
|
|
markdownContent: string
|
|
): Promise<string> => {
|
|
return await markdownToHtml(markdownContent || "");
|
|
};
|