diff --git a/lib/posts.ts b/lib/posts.ts new file mode 100644 index 0000000..432fa55 --- /dev/null +++ b/lib/posts.ts @@ -0,0 +1,29 @@ +import fs from 'fs'; +import path from 'path'; +import matter from 'gray-matter'; +import { MyMatters, Post } from 'types'; +import { sortByDate } from 'lib/utils'; + +/** + * Read all posts with matter info. + * @returns + */ +export const postLists = async (): Promise => { + const files = fs.readdirSync(path.join('pages/p')); + const posts = files + .map((filename) => { + const markdownWithMeta = fs.readFileSync( + path.join('pages/p', filename), + 'utf-8' + ); + const slug = filename.replace(/\.mdx$/, ''); + const { data: meta } = matter(markdownWithMeta); + return { + slug, + ...({ ...meta } as MyMatters), + }; + }) + .sort(sortByDate); + + return posts; +}; diff --git a/lib/utils/constant.ts b/lib/utils/constant.ts deleted file mode 100644 index 24a477c..0000000 --- a/lib/utils/constant.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const server = - process.env.NODE_ENV === 'development' - ? 'http://localhost:3000' - : 'https://rua.plus'; diff --git a/pages/api/posts.ts b/pages/api/posts.ts index 3244c08..74153ae 100644 --- a/pages/api/posts.ts +++ b/pages/api/posts.ts @@ -1,31 +1,13 @@ import type { NextApiRequest, NextApiResponse } from 'next'; -import fs from 'fs'; -import path from 'path'; -import matter from 'gray-matter'; -import { MyMatters, Post } from 'types'; -import { sortByDate } from 'lib/utils'; +import { Post } from 'types'; +import { postLists } from 'lib/posts'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { - const getPosts = () => { - const files = fs.readdirSync(path.join('pages/p')); - const posts = files - .map((filename) => { - const markdownWithMeta = fs.readFileSync( - path.join('pages/p', filename), - 'utf-8' - ); - const slug = filename.replace(/\.mdx$/, ''); - const { data: meta } = matter(markdownWithMeta); - return { - slug, - ...({ ...meta } as MyMatters), - }; - }) - .sort(sortByDate); - + const getPosts = async () => { + const posts = await postLists(); res.status(200).json(posts); }; diff --git a/pages/blog.tsx b/pages/blog.tsx index df5dd69..d040ac5 100644 --- a/pages/blog.tsx +++ b/pages/blog.tsx @@ -1,8 +1,7 @@ import MainLayout from 'layouts/MainLayout'; -import { Post } from 'types'; import { InferGetStaticPropsType } from 'next'; import { ReactElement } from 'react'; -import { server } from 'lib/utils/constant'; +import { postLists } from 'lib/posts'; const Blog = ({ posts }: InferGetStaticPropsType) => { return ( @@ -23,12 +22,9 @@ const Blog = ({ posts }: InferGetStaticPropsType) => { }; export const getStaticProps = async () => { - const response = await fetch(`${server}/api/posts`); - const posts = (await response.json()) as Post[]; - return { props: { - posts, + posts: await postLists(), }, }; };