Files
astroplate/scripts/jsonGenerator.js
T

81 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-04-17 12:50:29 +06:00
const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");
2024-05-14 16:23:32 +06:00
const languages = require("../src/config/language.json");
2023-12-11 15:00:43 +06:00
const JSON_FOLDER = "./.json";
2024-05-14 16:23:32 +06:00
const CONTENT_ROOT = "src/content";
const CONTENT_DEPTH = 3;
const BLOG_FOLDER = "blog";
2023-04-17 12:50:29 +06:00
// get data from markdown
const getData = (folder, groupDepth, langIndex = 0) => {
2024-05-14 16:23:32 +06:00
// get paths
const getPaths = languages
.map((lang, index) => {
const langFolder = lang.contentDir ? lang.contentDir : lang.languageCode;
const dir = path.join(CONTENT_ROOT, folder, langFolder);
2024-05-14 16:23:32 +06:00
return fs
.readdirSync(dir)
.filter(
(filename) =>
!filename.startsWith("-") &&
(filename.endsWith(".md") || filename.endsWith(".mdx")),
)
.map((filename) => {
const filepath = path.join(dir, filename);
const stats = fs.statSync(filepath);
const isFolder = stats.isDirectory();
2023-12-11 15:00:43 +06:00
2024-05-14 16:23:32 +06:00
if (isFolder) {
return getData(filepath, groupDepth, index);
2024-05-14 16:23:32 +06:00
} else {
const file = fs.readFileSync(filepath, "utf-8");
const { data, content } = matter(file);
const pathParts = filepath.split(path.sep);
const slug =
data.slug ||
pathParts
.slice(CONTENT_DEPTH)
.join("/")
.replace(/\.[^/.]+$/, "");
const group = pathParts[groupDepth];
2023-12-11 15:00:43 +06:00
2024-05-14 16:23:32 +06:00
return {
lang: languages[langIndex].languageCode,
2024-05-14 16:23:32 +06:00
group: group,
slug: slug,
frontmatter: data,
content: content,
};
}
});
})
.flat();
2023-12-11 15:00:43 +06:00
const publishedPages = getPaths.filter(
(page) => !page.frontmatter?.draft && page,
2023-04-17 12:50:29 +06:00
);
return publishedPages;
};
try {
2023-12-11 15:00:43 +06:00
// create folder if it doesn't exist
if (!fs.existsSync(JSON_FOLDER)) {
fs.mkdirSync(JSON_FOLDER);
2023-04-17 12:50:29 +06:00
}
2023-12-11 15:00:43 +06:00
// create json files
fs.writeFileSync(
`${JSON_FOLDER}/posts.json`,
2024-05-14 16:23:32 +06:00
JSON.stringify(getData(BLOG_FOLDER, 3)),
2023-12-11 15:00:43 +06:00
);
// merger json files for search
const posts = require(`../${JSON_FOLDER}/posts.json`);
const search = [...posts];
fs.writeFileSync(`${JSON_FOLDER}/search.json`, JSON.stringify(search));
2023-04-17 12:50:29 +06:00
} catch (err) {
console.error(err);
}