82 lines
2.5 KiB
TypeScript
82 lines
2.5 KiB
TypeScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import matter from 'gray-matter';
|
|
|
|
// 定义文章元数据类型
|
|
interface ArticleMetadata {
|
|
title: string;
|
|
date: string;
|
|
author: string;
|
|
category: string;
|
|
tags: string[];
|
|
locale: 'zh-CN' | 'zh-TW' | 'en';
|
|
description: string;
|
|
image: string;
|
|
excerpt: string;
|
|
slug: string;
|
|
featured: boolean;
|
|
}
|
|
|
|
// 定义文章类型
|
|
interface Article {
|
|
id: string;
|
|
slug: string;
|
|
metadata: ArticleMetadata;
|
|
content: string;
|
|
}
|
|
|
|
const docsDirectory = path.join(process.cwd(), 'docs');
|
|
|
|
export function getStaticArticles(locale: 'zh-CN' | 'zh-TW' | 'en' = 'zh-CN'): Article[] {
|
|
const localeDir = path.join(docsDirectory, locale);
|
|
|
|
if (!fs.existsSync(localeDir)) {
|
|
console.warn(`Docs directory not found for locale: ${locale}`);
|
|
return [];
|
|
}
|
|
|
|
try {
|
|
const fileNames = fs.readdirSync(localeDir);
|
|
const articles = fileNames
|
|
.filter((fileName: string) => fileName.endsWith('.md'))
|
|
.map((fileName: string) => {
|
|
const fullPath = path.join(localeDir, fileName);
|
|
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
|
const { data, content } = matter(fileContents);
|
|
const slug = fileName.replace(/\.md$/, '');
|
|
const id = slug;
|
|
|
|
return {
|
|
id,
|
|
slug,
|
|
metadata: {
|
|
...data,
|
|
slug,
|
|
locale,
|
|
} as ArticleMetadata,
|
|
content,
|
|
};
|
|
})
|
|
.sort((a, b) => {
|
|
const dateA = new Date(a.metadata.date);
|
|
const dateB = new Date(b.metadata.date);
|
|
return dateB.getTime() - dateA.getTime();
|
|
});
|
|
|
|
return articles;
|
|
} catch (error) {
|
|
console.error(`Error reading articles for locale ${locale}:`, error);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export function getStaticCategories(locale: 'zh-CN' | 'zh-TW' | 'en' = 'zh-CN'): string[] {
|
|
const articles = getStaticArticles(locale);
|
|
const categories = articles.map((article) => article.metadata.category);
|
|
return Array.from(new Set(categories));
|
|
}
|
|
|
|
export function getStaticArticleBySlug(slug: string, locale: 'zh-CN' | 'zh-TW' | 'en' = 'zh-CN'): Article | null {
|
|
const articles = getStaticArticles(locale);
|
|
return articles.find(article => article.slug === slug) || null;
|
|
}
|