jonbio/pages/blog/[...slug].js

66 lines
1.9 KiB
JavaScript
Raw Normal View History

import fs from 'fs'
2021-01-16 18:36:25 +08:00
import PageTitle from '@/components/PageTitle'
2021-01-09 17:50:45 +08:00
import generateRss from '@/lib/generate-rss'
2021-05-26 00:11:20 +08:00
import { MDXLayoutRenderer } from '@/components/MDXComponents'
import { formatSlug, getAllFilesFrontMatter, getFileBySlug, getFiles } from '@/lib/mdx'
2021-01-09 17:50:45 +08:00
export async function getStaticPaths() {
const posts = getFiles('blog')
2021-01-09 17:50:45 +08:00
return {
paths: posts.map((p) => ({
params: {
slug: formatSlug(p).split('/'),
2021-01-09 17:50:45 +08:00
},
})),
fallback: false,
}
}
export async function getStaticProps({ params }) {
const allPosts = await getAllFilesFrontMatter('blog')
const postIndex = allPosts.findIndex((post) => formatSlug(post.slug) === params.slug.join('/'))
2021-01-09 17:50:45 +08:00
const prev = allPosts[postIndex + 1] || null
const next = allPosts[postIndex - 1] || null
const post = await getFileBySlug('blog', params.slug)
2021-05-18 23:46:30 +08:00
const authorList = post.frontMatter.authors || ['default']
const authorPromise = authorList.map(async (author) => {
const authorResults = await getFileBySlug('authors', [author])
return authorResults.frontMatter
})
const authorDetails = await Promise.all(authorPromise)
2021-01-09 17:50:45 +08:00
// rss
const rss = generateRss(allPosts)
fs.writeFileSync('./public/index.xml', rss)
2021-05-16 15:56:39 +08:00
return { props: { post, authorDetails, prev, next } }
2021-01-09 17:50:45 +08:00
}
2021-05-16 15:56:39 +08:00
export default function Blog({ post, authorDetails, prev, next }) {
2021-01-09 17:50:45 +08:00
const { mdxSource, frontMatter } = post
return (
<>
2021-01-16 18:36:25 +08:00
{frontMatter.draft !== true ? (
2021-05-26 00:11:20 +08:00
<MDXLayoutRenderer
layout={frontMatter.layout || 'PostLayout'}
mdxSource={mdxSource}
frontMatter={frontMatter}
authorDetails={authorDetails}
prev={prev}
next={next}
/>
2021-01-16 18:36:25 +08:00
) : (
<div className="mt-24 text-center">
<PageTitle>
Under Construction{' '}
<span role="img" aria-label="roadwork sign">
🚧
</span>
</PageTitle>
</div>
2021-01-09 17:50:45 +08:00
)}
</>
)
}