From 530b4ffa8e7350fa8de1565b93bc2a2e53e1501e Mon Sep 17 00:00:00 2001 From: Hazem Krimi Date: Thu, 14 Jan 2021 23:33:44 +0100 Subject: [PATCH] Add helper functions to fetch blog posts data --- lib/blog.ts | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 lib/blog.ts diff --git a/lib/blog.ts b/lib/blog.ts new file mode 100644 index 0000000..a4c6c35 --- /dev/null +++ b/lib/blog.ts @@ -0,0 +1,56 @@ +import fs from 'fs'; +import path from 'path'; +import matter from 'gray-matter'; + +const blogPostsDirectory = path.join(process.cwd(), '_blog'); + +export const getBlogPosts = () => { + const fileNames = fs.readdirSync(blogPostsDirectory); + + const allBlogPostsData = fileNames.map(filename => { + const slug = filename.replace('.mdx', ''); + + const fullPath = path.join(blogPostsDirectory, filename); + const fileContents = fs.readFileSync(fullPath, 'utf8'); + const { data } = matter(fileContents); + + const options = { month: 'long', day: 'numeric', year: 'numeric' }; + const formattedDate = new Date(data.date).toLocaleDateString('en-IN', options); + + const frontmatter = { + ...data, + date: formattedDate + }; + return { + slug, + ...frontmatter + }; + }); + + return allBlogPostsData.sort((a, b) => { + if (new Date(a.date) < new Date(b.date)) { + return 1; + } else { + return -1; + } + }); +}; + +export const getBlogPostsSlugs = () => { + const fileNames = fs.readdirSync(blogPostsDirectory); + + return fileNames.map(filename => { + return { + params: { + slug: filename.replace('.mdx', '') + } + }; + }); +}; + +export const getBlogPostdata = async (slug: string) => { + const fullPath = path.join(blogPostsDirectory, `${slug}.mdx`); + const postContent = fs.readFileSync(fullPath, 'utf8'); + + return postContent; +};