initial
This commit is contained in:
55
src/lib/markdown.ts
Normal file
55
src/lib/markdown.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import matter from 'gray-matter';
|
||||
import { remark } from 'remark';
|
||||
import html from 'remark-html';
|
||||
|
||||
export interface Post {
|
||||
slug: string;
|
||||
title: string;
|
||||
date: string;
|
||||
tags: string[];
|
||||
summary: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
const postsDirectory = path.join(process.cwd(), 'posts');
|
||||
|
||||
export async function getPostBySlug(slug: string): Promise<Post> {
|
||||
const realSlug = slug.replace(/\.md$/, '');
|
||||
const fullPath = path.join(postsDirectory, `${realSlug}.md`);
|
||||
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
||||
const { data, content } = matter(fileContents);
|
||||
|
||||
const processedContent = await remark()
|
||||
.use(html)
|
||||
.process(content);
|
||||
|
||||
return {
|
||||
slug: realSlug,
|
||||
title: data.title,
|
||||
date: data.date,
|
||||
tags: data.tags || [],
|
||||
summary: data.summary,
|
||||
content: processedContent.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAllPosts(): Promise<Post[]> {
|
||||
const fileNames = fs.readdirSync(postsDirectory);
|
||||
const allPostsData = await Promise.all(
|
||||
fileNames
|
||||
.filter((fileName) => fileName.endsWith('.md'))
|
||||
.map(async (fileName) => {
|
||||
const slug = fileName.replace(/\.md$/, '');
|
||||
return getPostBySlug(slug);
|
||||
})
|
||||
);
|
||||
|
||||
return allPostsData.sort((a, b) => (a.date < b.date ? 1 : -1));
|
||||
}
|
||||
|
||||
export async function getPostsByTag(tag: string): Promise<Post[]> {
|
||||
const allPosts = await getAllPosts();
|
||||
return allPosts.filter((post) => post.tags.includes(tag));
|
||||
}
|
||||
Reference in New Issue
Block a user