import { promises as fs } from 'fs'; import path from 'path'; import marked from 'marked'; import markedOptions from './markedOptions'; marked.setOptions(markedOptions); interface PostMetadata { name: string; lastUpdated: string; } interface Post { directory: string; path: string; meta: PostMetadata; } export type { PostMetadata, Post }; async function getMetadata(postPath : string) : Promise { 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 { 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 { const markdownPath = path.join(post.path, 'main.md'); const markdown = await fs.readFile(markdownPath, 'utf8'); const html = marked(markdown); return html; } export { getPosts, getMarkdown, getPostFromDirectory };