From 745f7a50ebe2583b9badd371fc2a6f394148c88b Mon Sep 17 00:00:00 2001
From: Furkan Sahin <furkan-dev@proton.me>
Date: Wed, 21 Jul 2021 03:59:15 -0500
Subject: Dynamic markdown page generation with preloading

---
 utils/Posts.tsx | 40 +++++++++++++++++++++++++---------------
 1 file changed, 25 insertions(+), 15 deletions(-)

(limited to 'utils/Posts.tsx')

diff --git a/utils/Posts.tsx b/utils/Posts.tsx
index e82357a..d82467e 100644
--- a/utils/Posts.tsx
+++ b/utils/Posts.tsx
@@ -1,5 +1,9 @@
 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;
@@ -24,21 +28,24 @@ async function getMetadata(postPath : string) : Promise<PostMetadata> {
   return JSON.parse(postMetadata) as PostMetadata;
 }
 
-async function getPosts() : Promise<Post[]> {
-  const postsDirectory = path.join(process.cwd(), 'posts');
-  const directories = await fs.readdir(postsDirectory);
+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);
 
-  const posts = directories.map(async (directory) => {
-    const postPath = path.join(postsDirectory, directory);
-    
-    const meta = await getMetadata(postPath);
+  return {
+    directory,
+    path: postPath,
+    meta
+  };
+}
+
+async function getPosts() : Promise<Post[]> {
+  const directories = await fs.readdir(POST_PATH);
 
-    return {
-      directory,
-      path: postPath,
-      meta 
-    };
-  });
+  const posts = directories.map(getPostFromDirectory);
 
   return await Promise.all(posts);
 }
@@ -48,10 +55,13 @@ async function getMarkdown(post : Post) : Promise<string> {
 
   const markdown = await fs.readFile(markdownPath, 'utf8');
 
-  return markdown;
+  const html = marked(markdown);
+
+  return html;
 }
 
 export {
   getPosts,
-  getMetadata,
+  getMarkdown,
+  getPostFromDirectory
 };
\ No newline at end of file
-- 
cgit v1.2.3

