66 lines
1.8 KiB
TypeScript
66 lines
1.8 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(), 'posts');
|
|
|
|
export interface PostData {
|
|
slug: string;
|
|
title: string;
|
|
date: string;
|
|
tags: string[];
|
|
contentHtml: string;
|
|
description: string;
|
|
}
|
|
|
|
export function getAllPostSlugs(): string[] {
|
|
const fileNames = fs.readdirSync(postsDirectory);
|
|
return fileNames.map((fileName) => fileName.replace(/\.md$/, ''));
|
|
}
|
|
|
|
export function getSortedPostsData(): Omit<PostData, 'contentHtml'>[] {
|
|
const fileNames = fs.readdirSync(postsDirectory);
|
|
const allPostsData = fileNames.map((fileName) => {
|
|
const slug = fileName.replace(/\.md$/, '');
|
|
const fullPath = path.join(postsDirectory, fileName);
|
|
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
|
const matterResult = matter(fileContents);
|
|
|
|
return {
|
|
slug,
|
|
title: matterResult.data.title,
|
|
date: matterResult.data.date,
|
|
tags: matterResult.data.tags || [],
|
|
description: matterResult.data.description || '',
|
|
};
|
|
});
|
|
|
|
return allPostsData.sort((a, b) => {
|
|
if (a.date < b.date) {
|
|
return 1;
|
|
} else {
|
|
return -1;
|
|
}
|
|
});
|
|
}
|
|
|
|
export async function getPostData(slug: string): Promise<PostData> {
|
|
const fullPath = path.join(postsDirectory, `${slug}.md`);
|
|
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
|
const matterResult = matter(fileContents);
|
|
const processedContent = await remark()
|
|
.use(html)
|
|
.process(matterResult.content);
|
|
const contentHtml = processedContent.toString();
|
|
|
|
return {
|
|
slug,
|
|
contentHtml,
|
|
title: matterResult.data.title,
|
|
date: matterResult.data.date,
|
|
tags: matterResult.data.tags || [],
|
|
description: matterResult.data.description || '',
|
|
};
|
|
} |