-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
57 lines (47 loc) · 1.49 KB
/
api.ts
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
import fs from "fs";
import { join } from "path";
import matter from "gray-matter";
import CATEGORIES from "../constants/categories";
const articlesDirectory = join(process.cwd(), "_articles");
export const getArticleSlugs = () => {
return fs.readdirSync(articlesDirectory);
};
type Items = {
[key: string]: string;
};
export const getArticleBySlug = (slug: string, fields: string[] = []) => {
const realSlug = slug.replace(/\.md$/, "");
const fullPath = join(articlesDirectory, `${realSlug}.md`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const { data, content } = matter(fileContents);
const items: Items = {};
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 const getAllSlugs = (fields: string[] = []) => {
return getArticleSlugs().map((slug) => getArticleBySlug(slug, fields));
};
export const getCategoryBySlug = (slug: string, fields: string[] = []) => {
const slugs = getAllSlugs(fields);
return {
...CATEGORIES[slug],
slug: slug,
featured: CATEGORIES[slug].featured.map((article) =>
getArticleBySlug(article, ["title", "slug"])
),
subcategories: CATEGORIES[slug].subcategories.map((subcategory) => ({
title: subcategory,
articles: slugs.filter((slug) => slug.subcategory === subcategory),
})),
};
};