Second frontend, written in Next.JS + Typescript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.8 KiB

4 years ago
  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. const postsDirectory = path.join(process.cwd(), "posts")
  7. export function getSortedPostsData() {
  8. // Get file names under /posts
  9. const fileNames = fs.readdirSync(postsDirectory)
  10. const allPostsData = fileNames.map(fileName => {
  11. // Remove ".md" from file name to get id
  12. const id = fileName.replace(/\.md$/, "")
  13. // Read markdown file as string
  14. const fullPath = path.join(postsDirectory, fileName)
  15. const fileContents = fs.readFileSync(fullPath, "utf8")
  16. // Use gray-matter to parse the post metadata section
  17. const matterResult = matter(fileContents)
  18. // Combine the data with the id
  19. return {
  20. id,
  21. ...(matterResult.data as { date: string; title: string })
  22. }
  23. })
  24. // Sort posts by date
  25. return allPostsData.sort((a, b) => {
  26. if (a.date < b.date) {
  27. return 1
  28. } else {
  29. return -1
  30. }
  31. })
  32. }
  33. export function getAllPostIds() {
  34. const fileNames = fs.readdirSync(postsDirectory)
  35. return fileNames.map(fileName => {
  36. return {
  37. params: {
  38. id: fileName.replace(/\.md$/, "")
  39. }
  40. }
  41. })
  42. }
  43. export async function getPostData(id: string) {
  44. const fullPath = path.join(postsDirectory, `${id}.md`)
  45. const fileContents = fs.readFileSync(fullPath, "utf8")
  46. // Use gray-matter to parse the post metadata section
  47. const matterResult = matter(fileContents)
  48. // Use remark to convert markdown into HTML string
  49. const processedContent = await remark()
  50. .use(html)
  51. .process(matterResult.content)
  52. const contentHtml = processedContent.toString()
  53. // Combine the data with the id and contentHtml
  54. return {
  55. id,
  56. contentHtml,
  57. ...(matterResult.data as { date: string; title: string })
  58. }
  59. }