42 lines
940 B
TypeScript
42 lines
940 B
TypeScript
import fs from "fs"
|
|
import path from "path"
|
|
import matter from "gray-matter"
|
|
|
|
export interface Post {
|
|
slug: string
|
|
title: string
|
|
content: string
|
|
}
|
|
|
|
const postsDirectory = path.join(process.cwd(), "posts")
|
|
|
|
export async function getPost(slug: string): Promise<Post | null> {
|
|
try {
|
|
const fullPath = path.join(postsDirectory, `${slug}.md`)
|
|
|
|
// Try .md first, then .mdx
|
|
let fileContents: string
|
|
if (fs.existsSync(fullPath)) {
|
|
fileContents = fs.readFileSync(fullPath, "utf8")
|
|
} else {
|
|
const mdxPath = path.join(postsDirectory, `${slug}.mdx`)
|
|
if (fs.existsSync(mdxPath)) {
|
|
fileContents = fs.readFileSync(mdxPath, "utf8")
|
|
} else {
|
|
return null
|
|
}
|
|
}
|
|
|
|
const { data, content } = matter(fileContents)
|
|
|
|
return {
|
|
slug,
|
|
title: data.title || slug,
|
|
content,
|
|
}
|
|
} catch (error) {
|
|
console.error("Error reading post:", error)
|
|
return null
|
|
}
|
|
}
|