From 091f1c591bea7d606b255264b8a12dae4c9fbe3a Mon Sep 17 00:00:00 2001 From: Hazem Krimi Date: Thu, 14 Jan 2021 23:35:00 +0100 Subject: [PATCH] Add helper functions to fetch portfolio projects data --- lib/portfolio.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 lib/portfolio.ts diff --git a/lib/portfolio.ts b/lib/portfolio.ts new file mode 100644 index 0000000..d9143d0 --- /dev/null +++ b/lib/portfolio.ts @@ -0,0 +1,56 @@ +import fs from 'fs'; +import path from 'path'; +import matter from 'gray-matter'; + +const portfolioProjects = path.join(process.cwd(), '_portfolio'); + +export const getPortfolioProjects = () => { + const fileNames = fs.readdirSync(portfolioProjects); + + const allPortfolioProjectsData = fileNames.map(filename => { + const slug = filename.replace('.mdx', ''); + + const fullPath = path.join(portfolioProjects, 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 allPortfolioProjectsData.sort((a, b) => { + if (new Date(a.date) < new Date(b.date)) { + return 1; + } else { + return -1; + } + }); +}; + +export const getPortfolioPorjectsSlugs = () => { + const fileNames = fs.readdirSync(portfolioProjects); + + return fileNames.map(filename => { + return { + params: { + slug: filename.replace('.mdx', '') + } + }; + }); +}; + +export const getPortfolioProjectdata = async (slug: string) => { + const fullPath = path.join(portfolioProjects, `${slug}.mdx`); + const postContent = fs.readFileSync(fullPath, 'utf8'); + + return postContent; +};