|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | +import matter from 'gray-matter'; |
| 4 | +import { remark } from 'remark'; |
| 5 | +import html from 'remark-html'; |
| 6 | + |
| 7 | +const postsDirectory = path.join(process.cwd(), 'posts'); |
| 8 | + |
| 9 | +export function getSortedPostsData() { |
| 10 | + // Get file names under /posts |
| 11 | + const fileNames = fs.readdirSync(postsDirectory); |
| 12 | + const allPostsData = fileNames.map((fileName) => { |
| 13 | + // Remove ".md" from file name to get id |
| 14 | + const id = fileName.replace(/\.md$/, ''); |
| 15 | + |
| 16 | + // Read markdown file as string |
| 17 | + const fullPath = path.join(postsDirectory, fileName); |
| 18 | + const fileContents = fs.readFileSync(fullPath, 'utf8'); |
| 19 | + |
| 20 | + // Use gray-matter to parse the post metadata section |
| 21 | + const matterResult = matter(fileContents); |
| 22 | + |
| 23 | + // Combine the data with the id |
| 24 | + return { |
| 25 | + id, |
| 26 | + ...matterResult.data, |
| 27 | + }; |
| 28 | + }); |
| 29 | + // Sort posts by date |
| 30 | + return allPostsData.sort((a, b) => { |
| 31 | + if (a.date < b.date) { |
| 32 | + return 1; |
| 33 | + } else { |
| 34 | + return -1; |
| 35 | + } |
| 36 | + }); |
| 37 | +} |
| 38 | + |
| 39 | +export function getAllPostIds() { |
| 40 | + const fileNames = fs.readdirSync(postsDirectory); |
| 41 | + |
| 42 | + // Returns an array that looks like this: |
| 43 | + // [ |
| 44 | + // { |
| 45 | + // params: { |
| 46 | + // id: 'ssg-ssr' |
| 47 | + // } |
| 48 | + // }, |
| 49 | + // { |
| 50 | + // params: { |
| 51 | + // id: 'pre-rendering' |
| 52 | + // } |
| 53 | + // } |
| 54 | + // ] |
| 55 | + return fileNames.map((fileName) => { |
| 56 | + return { |
| 57 | + params: { |
| 58 | + id: ['prefix', fileName.replace(/\.md$/, '')], |
| 59 | + }, |
| 60 | + }; |
| 61 | + }); |
| 62 | +} |
| 63 | + |
| 64 | +export async function getPostData(id) { |
| 65 | + const fullPath = path.join(postsDirectory, `${id[1]}.md`); |
| 66 | + |
| 67 | + const fileContents = fs.readFileSync(fullPath, 'utf8'); |
| 68 | + |
| 69 | + // Use gray-matter to parse the post metadata section |
| 70 | + const matterResult = matter(fileContents); |
| 71 | + |
| 72 | + // Use remark to convert markdown into HTML string |
| 73 | + const processedContent = await remark().use(html).process(matterResult.content); |
| 74 | + const contentHtml = processedContent.toString(); |
| 75 | + |
| 76 | + // Combine the data with the id and contentHtml |
| 77 | + return { |
| 78 | + id, |
| 79 | + contentHtml, |
| 80 | + ...matterResult.data, |
| 81 | + }; |
| 82 | +} |
0 commit comments