import { cwd } from "process";
import { join, resolve } from "path";
import { readFile } from "fs/promises";
import matter from "gray-matter";
import tocGenerator from "markdown-toc";
import type { Page } from "../../types";
import * as paths from "../../../paths";
export async function getDocFileContent(
sectionSlug: string,
pageSlug: string,
ext: string
): Promise<Page> {
try {
const filePath = resolve(
join(paths.ROOT_FOLDER, "docs", sectionSlug, `${pageSlug}.${ext}`)
);
const content = await readFile(filePath, { encoding: "utf-8" });
const ymlMatter = matter(content, { language: "yaml" });
const toc = tocGenerator(ymlMatter.content).json as {
content: string;
slug: string;
lvl: number;
}[];
return {
slug: pageSlug,
content: ymlMatter.content as string,
tableOfContent: toc.map((entry) => ({
title: entry.content,
targetAnchor: entry.slug,
depth: entry.lvl,
})),
metas: ymlMatter.data,
};
} catch (err) {
const workingDir = cwd();
const error = err as Error;
return {
slug: pageSlug,
content: `# ${
error.name || "InternalServerError"
}\n\n> ${error.message.replace(`${workingDir}/docs`, "")}`,
tableOfContent: [],
metas: {
error,
},
};
}
}