www-new/lib/organized-content.ts

41 lines
1.1 KiB
TypeScript

import fs from "fs/promises";
import path from "path";
import matter from "gray-matter";
import { serialize } from "next-mdx-remote/serialize";
const BASE_PATH = "content";
export async function getSectionNamesForPage(page: string) {
const sectionDir = path.join(BASE_PATH, page);
return (await fs.readdir(sectionDir))
.filter((name) => name.endsWith(".md"))
.map((name) => name.slice(0, -".md".length));
}
export async function getSectionsForPage(page: string) {
const names = await getSectionNamesForPage(page);
const sections = await Promise.all(
names.map(async (name) => ({
name,
data: await getSectionForPage(page, name),
}))
);
return sections.sort((a, b) => a.data.index - b.data.index);
}
export async function getSectionForPage(page: string, section: string) {
const raw = await fs.readFile(
path.join(BASE_PATH, page, `${section}.md`),
"utf-8"
);
const { content, data } = matter(raw);
return {
content: await serialize(content),
title: data.title as string,
index: data.index as number,
};
}