55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
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(), 'src/posts');
|
|
|
|
export function getAllPosts() {
|
|
const fileNames = fs.readdirSync(postsDirectory);
|
|
|
|
return fileNames
|
|
.map((fileName) => {
|
|
const slug = fileName.replace(/\.md$/, '');
|
|
const fullPath = path.join(postsDirectory, fileName);
|
|
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
|
|
|
const { data } = matter(fileContents);
|
|
|
|
return {
|
|
slug,
|
|
title: data.title,
|
|
date: data.date,
|
|
excerpt: data.excerpt,
|
|
};
|
|
})
|
|
.sort((a, b) => (a.date < b.date ? 1 : -1));
|
|
}
|
|
|
|
export async function getPostBySlug(slug: string) {
|
|
const fullPath = path.join(postsDirectory, `${slug}.md`);
|
|
if (!fs.existsSync(fullPath)) {
|
|
throw new Error(`Post not found: ${slug}`);
|
|
}
|
|
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
|
|
|
const { data, content } = matter(fileContents);
|
|
|
|
const processedContent = await remark().use(html).process(content);
|
|
const contentHtml = processedContent.toString();
|
|
|
|
return {
|
|
slug,
|
|
contentHtml,
|
|
title: data.title,
|
|
date: data.date,
|
|
};
|
|
}
|
|
|
|
export const getAllSlugs = () => {
|
|
return fs.readdirSync(postsDirectory).map((fileName) => ({
|
|
params: { slug: fileName.replace(/\.md$/, '') },
|
|
}));
|
|
};
|