Created
August 15, 2020 04:13
-
-
Save sreetamdas/9f25fd13de8d812028485547a1dbcf33 to your computer and use it in GitHub Desktop.
get blog posts from MDX files into an index file
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 path from "path"; | |
export const getPostsData = () => { | |
const META = /export\s+const\s+meta\s+=\s+(\{(\n|.)*?\n\})/; | |
const DIR = path.join(process.cwd(), "content/blog"); | |
const files = fs.readdirSync(DIR).filter((file) => file.endsWith(".mdx")); | |
const postsData: Array<TBlogPost> = files | |
.map((file) => { | |
const name = path.join(DIR, file); | |
const contents = fs.readFileSync(name, "utf8"); | |
const match = META.exec(contents); | |
if (!match || typeof match[1] !== "string") | |
throw new Error(`${name} needs to export const meta = {}`); | |
const meta = eval("(" + match[1] + ")"); | |
return { | |
...meta, | |
slug: file.replace(/\.mdx?$/, ""), | |
}; | |
}) | |
.filter( | |
(meta) => process.env.NODE_ENV === "development" || meta.published | |
) | |
.sort((a, b) => { | |
return ( | |
new Date(b.publishedAt).getTime() - | |
new Date(a.publishedAt).getTime() | |
); | |
}); | |
return postsData; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment