import { NextRequest, NextResponse } from 'next/server'; import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; // 为静态导出生成参数 export async function generateStaticParams() { // 返回所有可能的consultation ID const consultationIds = ['cloud-migration', 'aws-optimization', 'security-audit']; return consultationIds.map((id) => ({ id, })); } const CACHE_DURATION = process.env.NODE_ENV === 'development' ? 0 : 60; // 开发环境10秒,生产环境60秒 interface CacheStore { [key: string]: { data: any; timestamp: number; }; } let cache: CacheStore = {}; function getCachedData(key: string, fetchFn: () => T): T { const now = Date.now(); const cached = cache[key]; if (cached && now - cached.timestamp < CACHE_DURATION * 1000) { return cached.data; } const data = fetchFn(); cache[key] = { data, timestamp: now, }; return data; } const docsDirectory = path.join(process.cwd(), 'data/consultations'); function getConsultationById(id: string, locale: 'zh-CN' | 'zh-TW' | 'en') { const fileName = `${id}.${locale}.md`; const fullPath = path.join(docsDirectory, fileName); if (!fs.existsSync(fullPath)) { return null; } const fileContents = fs.readFileSync(fullPath, 'utf8'); const { data } = matter(fileContents); return { id, metadata: { ...data, }, }; } export async function GET( request: NextRequest, { params }: { params: { id: string } } ) { const { searchParams } = new URL(request.url); const locale = (searchParams.get('locale') as 'zh-CN' | 'zh-TW' | 'en') || 'zh-CN'; const { id } = params; try { const cacheKey = `consultation:${id}:${locale}`; const result = getCachedData(cacheKey, () => { const consultation = getConsultationById(id, locale); if (!consultation) { return null; } return { consultation, }; }); if (!result) { return NextResponse.json({ error: 'Consultation not found' }, { status: 404 }); } // Set cache control headers const response = NextResponse.json(result); response.headers.set('Cache-Control', `public, s-maxage=${CACHE_DURATION}, stale-while-revalidate`); return response; } catch (error) { console.error('Error fetching consultation:', error); return NextResponse.json({ error: 'Failed to fetch consultation' }, { status: 500 }); } }