63 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-09-16 17:19:58 +08:00
import { NextRequest, NextResponse } from 'next/server';
import { getStaticArticleBySlug, getStaticArticles } from '../../../../lib/static-data';
// 为静态导出生成参数
export async function generateStaticParams() {
const locales = ['zh-CN', 'zh-TW', 'en'];
const allSlugs = new Set<string>();
// 收集所有语言的文章slug
for (const locale of locales) {
try {
const articles = getStaticArticles(locale as 'zh-CN' | 'zh-TW' | 'en');
articles.forEach(article => allSlugs.add(article.slug));
} catch (error) {
console.warn(`Failed to get articles for locale ${locale}:`, error);
}
}
return Array.from(allSlugs).map((slug) => ({
slug,
}));
}
export async function GET(
request: NextRequest,
{ params }: { params: { slug: string } }
) {
try {
const { searchParams } = new URL(request.url);
const locale = searchParams.get('locale') || 'zh-CN';
const slug = params.slug;
// 映射locale格式
const mappedLocale = locale === 'zh' ? 'zh-CN' : locale as 'zh-CN' | 'zh-TW' | 'en';
// 获取指定文章
const article = getStaticArticleBySlug(slug, mappedLocale);
if (!article) {
return NextResponse.json(
{ error: 'Article not found' },
{ status: 404 }
);
}
// 获取相关文章
const allArticles = getStaticArticles(mappedLocale);
const relatedArticles = allArticles
.filter(a => a.slug !== slug && a.metadata.category === article.metadata.category)
.slice(0, 3);
return NextResponse.json({
article,
relatedArticles
});
} catch (error) {
console.error('Error fetching article:', error);
return NextResponse.json(
{ error: 'Failed to fetch article' },
{ status: 500 }
);
}
}