forked from pythonindia/inpycon2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpages.js
41 lines (34 loc) · 1.04 KB
/
pages.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import fs from "fs";
import { join } from "path";
import matter from "gray-matter";
export function getPostSlugs(directory) {
const postsDirectory = join(process.cwd(), directory);
return fs.readdirSync(postsDirectory);
}
export function getPostBySlug(postsDirectory, slug, fields = []) {
const realSlug = slug.replace(/\.md$/, "");
const fullPath = join(postsDirectory, `${realSlug}.md`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(fileContents);
const items = {};
// Ensure only the minimal needed data is exposed
fields.forEach((field) => {
if (field === "slug") {
items[field] = realSlug;
}
if (field === "content") {
items[field] = content;
}
if (typeof data[field] !== "undefined") {
items[field] = data[field];
}
});
return items;
}
export function getAllPosts(postsDirectory, fields) {
const slugs = getPostSlugs(postsDirectory);
const posts = slugs.map((slug) =>
getPostBySlug(postsDirectory, slug, fields)
);
return posts;
}