Skip to content

Commit

Permalink
动态路由 & api route
Browse files Browse the repository at this point in the history
  • Loading branch information
wenj committed Feb 18, 2022
1 parent 7d44a9e commit 2263be1
Show file tree
Hide file tree
Showing 14 changed files with 938 additions and 2 deletions.
6 changes: 6 additions & 0 deletions components/date/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { parseISO, format } from 'date-fns'

export default function Date({ dateString }) {
const date = parseISO(dateString)
return <time dateTime={dateString}>{format(date, 'LLLL d, yyyy')}</time>
}
3 changes: 2 additions & 1 deletion components/layout/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,5 @@ export default function Layout({ children, home }) {
)}
</div>
)
}
}

76 changes: 76 additions & 0 deletions lib/posts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
import { remark } from 'remark'
import html from 'remark-html'

const postsDirectory = path.join(process.cwd(), 'pages/posts')

export function getSortedPostsData() {
// Get file names under /posts
const fileNames = fs.readdirSync(postsDirectory)
const allPostsData = fileNames
.filter(file => /\.md$/.test(file))
.map(fileName => {
// Remove ".md" from file name to get id
const id = fileName.replace(/\.md$/, '')

// Read markdown file as string
const fullPath = path.join(postsDirectory, fileName)
const fileContents = fs.readFileSync(fullPath, 'utf8')

// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents)

// Combine the data with the id
return {
id,
...matterResult.data
}
})

// Sort posts by date
return allPostsData.sort(({ date: a }, { date: b }) => {
if (a < b) {
return 1
} else if (a > b) {
return -1
} else {
return 0
}
})
}

export async function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`)
const fileContents = fs.readFileSync(fullPath, 'utf8')

// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents)

const processedContent = await remark()
.use(html)
.process(matterResult.content)
const contentHtml = processedContent.toString()

// Combine the data with the id
return {
id,
contentHtml,
...matterResult.data
}
}

export function getAllPostIds() {
const fileNames = fs.readdirSync(postsDirectory)

return fileNames
.filter(file => /\.md$/.test(file))
.map(fileName => {
return {
params: {
id: fileName.replace(/\.md$/, '')
}
}
})
}
Loading

0 comments on commit 2263be1

Please sign in to comment.