lesssagoo
This commit is contained in:
@@ -3,6 +3,7 @@ import path from 'path';
|
||||
import matter from 'gray-matter';
|
||||
import { remark } from 'remark';
|
||||
import html from 'remark-html';
|
||||
import chokidar from 'chokidar';
|
||||
|
||||
export interface Post {
|
||||
slug: string;
|
||||
@@ -11,15 +12,23 @@ export interface Post {
|
||||
tags: string[];
|
||||
summary: string;
|
||||
content: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
const postsDirectory = path.join(process.cwd(), 'posts');
|
||||
|
||||
// Function to get file creation date
|
||||
function getFileCreationDate(filePath: string): Date {
|
||||
const stats = fs.statSync(filePath);
|
||||
return stats.birthtime;
|
||||
}
|
||||
|
||||
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 createdAt = getFileCreationDate(fullPath);
|
||||
|
||||
const processedContent = await remark()
|
||||
.use(html)
|
||||
@@ -32,6 +41,7 @@ export async function getPostBySlug(slug: string): Promise<Post> {
|
||||
tags: data.tags || [],
|
||||
summary: data.summary,
|
||||
content: processedContent.toString(),
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -46,10 +56,45 @@ export async function getAllPosts(): Promise<Post[]> {
|
||||
})
|
||||
);
|
||||
|
||||
return allPostsData.sort((a, b) => (a.date < b.date ? 1 : -1));
|
||||
// Sort by creation date (newest first)
|
||||
return allPostsData.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
||||
}
|
||||
|
||||
export async function getPostsByTag(tag: string): Promise<Post[]> {
|
||||
const allPosts = await getAllPosts();
|
||||
return allPosts.filter((post) => post.tags.includes(tag));
|
||||
}
|
||||
// File watcher setup
|
||||
let watcher: chokidar.FSWatcher | null = null;
|
||||
let onChangeCallback: (() => void) | null = null;
|
||||
|
||||
export function watchPosts(callback: () => void) {
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
onChangeCallback = callback;
|
||||
watcher = chokidar.watch(postsDirectory, {
|
||||
ignored: /(^|[\/\\])\../, // ignore dotfiles
|
||||
persistent: true
|
||||
});
|
||||
|
||||
watcher
|
||||
.on('add', handleFileChange)
|
||||
.on('change', handleFileChange)
|
||||
.on('unlink', handleFileChange);
|
||||
}
|
||||
|
||||
function handleFileChange() {
|
||||
if (onChangeCallback) {
|
||||
onChangeCallback();
|
||||
}
|
||||
}
|
||||
|
||||
export function stopWatching() {
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
watcher = null;
|
||||
}
|
||||
onChangeCallback = null;
|
||||
}
|
||||
Reference in New Issue
Block a user