website/app/utils/posts.server.ts
2024-02-05 17:41:19 +01:00

71 lines
1.7 KiB
TypeScript

import { remarkCodeHike } from "@code-hike/mdx";
import { readdir, readFile } from "fs/promises";
import { bundleMDX } from "mdx-bundler";
type FrontMatter = {
title: string;
description: string;
published: string;
};
export const getMdxFile = async (file: string) => {
return bundleMDX<FrontMatter>({
source: (await readFile(`posts/${file}.mdx`)).toString(),
mdxOptions(options) {
return {
rehypePlugins: [...(options.rehypePlugins ?? [])],
remarkPlugins: [
...(options.remarkPlugins ?? []),
[
remarkCodeHike,
{
theme: "one-dark-pro",
lineNumbers: true,
showCopyButton: true,
autoImport: true,
},
],
],
};
},
});
};
export const findPosts = async () => {
const files = await readdir(`posts`);
const posts: (FrontMatter & {
filename: string;
})[] = [];
for (const file of files.filter((file) => file.endsWith(".mdx"))) {
const { frontmatter } = await bundleMDX<FrontMatter>({
source: (await readFile(`posts/${file}`)).toString(),
mdxOptions() {
return {
remarkPlugins: [
[
remarkCodeHike,
{
theme: "one-dark-pro",
lineNumbers: true,
showCopyButton: true,
autoImport: true,
},
],
],
};
},
});
posts.push({
filename: file.replace(".mdx", ""),
description: frontmatter.description,
title: frontmatter.title,
published: frontmatter.published,
});
}
return posts.sort((a, b) =>
new Date(a.published) > new Date(b.published) ? -1 : 1,
);
};