mirror of
https://github.com/LukeHagar/unicorn-utterances.git
synced 2025-12-10 04:22:06 +00:00
Add initial migration to NextJS
This commit is contained in:
47
lib/api.ts
Normal file
47
lib/api.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import fs from 'fs'
|
||||
import { join } from 'path'
|
||||
import matter from 'gray-matter'
|
||||
|
||||
export const postsDirectory = join(process.cwd(), 'content/blog')
|
||||
|
||||
export function getPostSlugs() {
|
||||
return fs.readdirSync(postsDirectory)
|
||||
}
|
||||
|
||||
export function getPostBySlug(slug: string, fields: string[] = []) {
|
||||
const realSlug = slug.replace(/\.md$/, '')
|
||||
const fullPath = join(postsDirectory, realSlug, `index.md`)
|
||||
const fileContents = fs.readFileSync(fullPath, 'utf8')
|
||||
const { data, content } = matter(fileContents)
|
||||
|
||||
type Items = {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
const items: Items = {}
|
||||
|
||||
// Ensure only the minimal needed data is exposed
|
||||
fields.forEach((field) => {
|
||||
if (field === 'slug') {
|
||||
items[field] = realSlug
|
||||
}
|
||||
if (field === 'content') {
|
||||
items[field] = content
|
||||
}
|
||||
|
||||
if (typeof data[field] !== 'undefined') {
|
||||
items[field] = data[field]
|
||||
}
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
export function getAllPosts(fields: string[] = []) {
|
||||
const slugs = getPostSlugs()
|
||||
const posts = slugs
|
||||
.map((slug) => getPostBySlug(slug, fields))
|
||||
// sort posts by date in descending order
|
||||
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1))
|
||||
return posts
|
||||
}
|
||||
Reference in New Issue
Block a user