MDX Starter (#3)

Reviewed-on: mthomson/michaelthomson#3
Co-authored-by: Michael Thomson <michael@michaelthomson.dev>
Co-committed-by: Michael Thomson <michael@michaelthomson.dev>
This commit is contained in:
2024-01-18 14:01:49 +00:00
committed by mthomson
parent a9c847ad0b
commit a25eb1d730
8 changed files with 1529 additions and 90 deletions

40
lib/posts.ts Normal file
View File

@@ -0,0 +1,40 @@
import fs from "fs"
import { join } from "path"
import matter from 'gray-matter'
const postsDirectory = join(process.cwd(), "posts");
export function getPostSlugs() {
const fileNames = fs.readdirSync(postsDirectory);
return fileNames.map(filename => filename.replace(/\.mdx$/, ""))
}
export function getPostBySlug(slug: string, fields: string[] = []) {
const fullPath = join(postsDirectory, `${slug}.mdx`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(fileContents)
type Items = {
[key: string]: string;
}
const items: Items = {};
fields.forEach((field) => {
if (field === "slug") {
items[field] = slug;
} else if (field === "content") {
items[field] = content;
} else if (typeof data[field] !== undefined) {
items[field] = data[field];
}
});
return items;
}
export function getAllPosts(fields: string[] = []) {
const slugs = getPostSlugs();
const posts = slugs.map((slug) => getPostBySlug(slug, fields));
return posts;
}