consolidate mdx file parsing

This commit is contained in:
2022-01-03 17:53:47 -05:00
parent d2b71887b4
commit 3864a57d1a
9 changed files with 59 additions and 68 deletions
+19 -16
View File
@@ -1,30 +1,33 @@
import fs from "fs";
import path from "path";
import matter from "gray-matter";
import { format, parseISO } from "date-fns";
import * as config from "./config";
import { NOTES_DIR, baseUrl } from "./config";
export const getNoteData = (file: string) => {
const slug = file.replace(/\.mdx$/, "");
const fullPath = path.join(process.cwd(), config.NOTES_DIR, `${slug}.mdx`);
const contents = fs.readFileSync(fullPath, "utf8");
const { data } = matter(contents);
export const getNoteData = (slug: string) => {
const fullPath = path.join(process.cwd(), NOTES_DIR, `${slug}.mdx`);
const rawContent = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(rawContent);
return {
...data,
slug,
permalink: `${config.baseUrl}/notes/${slug}/`,
date: parseISO(data.date).toISOString(), // validate/normalize the date string provided from front matter
year: parseInt(format(parseISO(data.date), "yyyy")), // parse years here so it's easier to group them on list page
frontMatter: {
...data,
slug,
permalink: `${baseUrl}/notes/${slug}/`,
date: new Date(data.date).toISOString(), // validate/normalize the date string provided from front matter
},
content,
};
};
// all .mdx files in NOTES_DIR
export const getNoteFiles = () =>
fs.readdirSync(path.join(process.cwd(), config.NOTES_DIR)).filter((notePath) => /\.mdx$/.test(notePath));
export const getNoteSlugs = () =>
fs
.readdirSync(path.join(process.cwd(), NOTES_DIR))
.filter((file) => /\.mdx$/.test(file))
.map((noteFile) => noteFile.replace(/\.mdx$/, ""));
export const getAllNotes = () =>
getNoteFiles()
.map((file) => getNoteData(file))
getNoteSlugs()
.map((slug) => getNoteData(slug).frontMatter)
// sort notes by date in descending order
.sort((note1: any, note2: any) => (note1.date > note2.date ? -1 : 1));