forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmdx.ts
More file actions
49 lines (42 loc) · 1.26 KB
/
Copy pathmdx.ts
File metadata and controls
49 lines (42 loc) · 1.26 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
49
import fs from "fs/promises";
import path from "path";
import matter from "gray-matter";
export interface MdxDocument {
slug: string;
title: string;
date?: string;
content: string;
excerpt?: string;
}
const CONTENT_DIR = path.join(process.cwd(), "content");
export async function getMdxBySlug(slug: string): Promise<MdxDocument | null> {
try {
const filePath = path.join(CONTENT_DIR, `${slug}.mdx`);
const raw = await fs.readFile(filePath, "utf-8");
const { data, content } = matter(raw);
return {
slug,
title: String(data.title ?? slug),
date: data.date ? String(data.date) : undefined,
excerpt: data.excerpt ? String(data.excerpt) : undefined,
content,
};
} catch {
return null;
}
}
export async function listMdxDocuments(): Promise<MdxDocument[]> {
try {
const files = await fs.readdir(CONTENT_DIR);
const docs: MdxDocument[] = [];
for (const file of files) {
if (!file.endsWith(".mdx")) continue;
const slug = file.replace(/\.mdx$/, "");
const doc = await getMdxBySlug(slug);
if (doc) docs.push(doc);
}
return docs.sort((a, b) => (b.date && a.date ? b.date.localeCompare(a.date) : 0));
} catch {
return [];
}
}