Created
May 12, 2020 09:15
-
-
Save ademilter/5a5085585bfc80d024b0b26003b4b464 to your computer and use it in GitHub Desktop.
get blog-post with sort date for next js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs' | |
import matter from 'gray-matter' | |
import { DateTime } from 'luxon' | |
export default function getBlogPostData(count = 999) { | |
const files = fs.readdirSync(`${process.cwd()}/content/posts`) | |
const posts = files.map((filename) => { | |
const markdownWithMetadata = fs | |
.readFileSync(`content/posts/${filename}`) | |
.toString() | |
const { data } = matter(markdownWithMetadata) | |
const formattedDate = data.date.toLocaleDateString() | |
const frontmatter = { | |
...data, | |
date: formattedDate | |
} | |
return { | |
slug: filename.replace('.md', ''), | |
frontmatter | |
} | |
}) | |
const postDataSortByDate = posts.sort((a, b) => { | |
const beforeDate = DateTime.fromFormat(a.frontmatter.date, 'M/d/yyyy') | |
const afterDate = DateTime.fromFormat(b.frontmatter.date, 'M/d/yyyy') | |
return afterDate - beforeDate | |
}) | |
return { | |
props: { | |
posts: postDataSortByDate.splice(0, count) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment