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
86
87
88
89
90
91
92
93
|
import { promises as fs } from 'fs';
import path from 'path';
// @ts-ignore
import { Marked } from 'marked';
import { markedHighlight } from 'marked-highlight';
import markedOptions from './markedOptions';
import { renderer, hooks } from '../loaders/marked-renderer.js';
const hljs = require('highlight.js');
const marker = new Marked(
markedHighlight(markedOptions),
{ renderer, hooks }
);
interface PostMetadata {
name: string;
lastUpdated: string;
}
interface Post {
directory: string;
path: string;
meta: PostMetadata;
}
export type {
PostMetadata,
Post
};
async function getMetadata(postPath : string) : Promise<PostMetadata> {
const metaPath = path.join(postPath, 'meta.json');
const postMetadata = await fs.readFile(metaPath, 'utf8');
return JSON.parse(postMetadata) as PostMetadata;
}
const POST_PATH = path.join(process.cwd(), 'posts');
async function getPostFromDirectory(directory : string) {
const postPath = path.join(POST_PATH, directory);
const meta = await getMetadata(postPath);
return {
directory,
path: postPath,
meta
};
}
async function getPosts() : Promise<Post[]> {
const directories = await fs.readdir(POST_PATH);
const posts = await Promise.all(directories.map(getPostFromDirectory));
return posts.sort((post_a, post_b) => {
const a = new Date(post_a.meta.lastUpdated);
const b = new Date(post_b.meta.lastUpdated);
if(a === b)
return 0;
if(a > b)
return -1;
return 1;
});
}
async function getMarkdown(post : Post) : Promise<string> {
const markdownPath = path.join(post.path, 'main.md');
const markdown = await fs.readFile(markdownPath, 'utf8');
const html = marker.parse(markdown);
if(html === undefined) {
return '';
} else {
return html as string;
}
}
export {
getPosts,
getMarkdown,
getPostFromDirectory
};
|