-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathjsonGenerator.js
85 lines (76 loc) · 2.54 KB
/
jsonGenerator.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");
const languages = require("../src/config/language.json");
const JSON_FOLDER = "./.json";
const CONTENT_ROOT = "src/content";
const CONTENT_DEPTH = 3;
const BLOG_FOLDER = "blog";
// get data from markdown
const getData = (folder, groupDepth, langIndex = 0) => {
const getPaths = languages
.map((lang, index) => {
const langFolder = lang.contentDir ? lang.contentDir : lang.languageCode;
const dir = path.join(CONTENT_ROOT, folder, langFolder);
return fs
.readdirSync(dir)
.filter(
(filename) =>
!filename.startsWith("-") &&
(filename.endsWith(".md") || filename.endsWith(".mdx")),
)
.flatMap((filename) => {
const filepath = path.join(dir, filename);
const stats = fs.statSync(filepath);
const isFolder = stats.isDirectory();
if (isFolder) {
return getData(filepath, groupDepth, index);
} else {
const file = fs.readFileSync(filepath, "utf-8");
const { data, content } = matter(file);
const pathParts = filepath.split(path.sep);
let slug;
if (data.slug) {
const slugParts = data.slug.split("/");
slugParts[0] = BLOG_FOLDER;
slug = slugParts.join("/");
} else {
slug = pathParts
.slice(CONTENT_DEPTH)
.join("/")
.replace(/\.[^/.]+$/, "");
slug = `${BLOG_FOLDER}/${slug.split("/").slice(1).join("/")}`;
}
data.slug = slug;
const group = "blog";
return {
lang: languages[index].languageCode, // Set the correct language code dynamically
group: group,
slug: data.slug,
frontmatter: data,
content: content,
};
}
});
})
.flat();
const publishedPages = getPaths.filter((page) => !page.frontmatter?.draft);
return publishedPages;
};
try {
// create folder if it doesn't exist
if (!fs.existsSync(JSON_FOLDER)) {
fs.mkdirSync(JSON_FOLDER);
}
// create json files
fs.writeFileSync(
`${JSON_FOLDER}/posts.json`,
JSON.stringify(getData(BLOG_FOLDER, 3)),
);
// merge json files for search
const posts = require(`../${JSON_FOLDER}/posts.json`);
const search = [...posts];
fs.writeFileSync(`${JSON_FOLDER}/search.json`, JSON.stringify(search));
} catch (err) {
console.error(err);
}