-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
48 lines (37 loc) · 1.13 KB
/
utils.js
File metadata and controls
48 lines (37 loc) · 1.13 KB
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
42
43
44
45
46
47
48
import fs from "fs";
import { join } from "path";
import matter from "gray-matter";
const storiesDirectory = join(process.cwd(), "stories");
function getStoryFileNames() {
return fs.readdirSync(storiesDirectory);
}
function getStoryBySlug(slug, fields = []) {
return getStoryByFileName(`${slug}.md`, fields);
}
function getStoryByFileName(fileName, fields = []) {
const slug = fileName.replace(/\.md$/, "");
const fullPath = join(storiesDirectory, `${fileName}`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(fileContents);
const fullStory = {
slug,
content,
...data,
};
const story = fields.reduce(
(storySoFar, field) =>
Object.assign(storySoFar, { [field]: fullStory[field] }),
{}
);
return story;
}
function getAllStories(fields = []) {
const fileNames = getStoryFileNames().filter((fileName) =>
/.+\.md$/.test(fileName)
);
const stories = fileNames
.map((fileName) => getStoryByFileName(fileName, fields))
.sort((story1, story2) => (story1.date > story2.date ? -1 : 1));
return stories;
}
export { getAllStories, getStoryBySlug };