89 lines
3.4 KiB
TypeScript
Raw Normal View History

2025-09-16 16:15:57 +08:00
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
interface ArticleMeta {
id: string;
category: string;
title: string;
excerpt: string;
author: string;
date: string;
readTime: number;
}
export async function GET(request: NextRequest) {
try {
const contentDir = path.join(process.cwd(), 'content');
const articles: ArticleMeta[] = [];
if (!fs.existsSync(contentDir)) {
return NextResponse.json(articles);
}
const folders = fs.readdirSync(contentDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
for (const folder of folders) {
const articleDir = path.join(contentDir, folder);
const files = fs.readdirSync(articleDir);
// 优先使用中文内容,如果没有则使用英文
let contentFile = '';
if (files.includes('zh.md')) {
contentFile = 'zh.md';
} else if (files.includes('en.md')) {
contentFile = 'en.md';
} else if (files.includes('zh-tw.md')) {
contentFile = 'zh-tw.md';
}
if (contentFile) {
const filePath = path.join(articleDir, contentFile);
const content = fs.readFileSync(filePath, 'utf-8');
// 从 Markdown 内容中提取元数据
const titleMatch = content.match(/^#\s+(.+)$/m);
const title = titleMatch ? titleMatch[1] : folder;
// 提取摘要(第一段非标题内容)
const lines = content.split('\n').filter(line =>
line.trim() && !line.startsWith('#') && !line.startsWith('---')
);
const excerpt = lines[0] || title;
// 根据文件夹名称推断分类
let category = 'tech';
if (folder.includes('ecs') || folder.includes('rds') || folder.includes('oss')) {
category = 'product';
} else if (folder.includes('deployment') || folder.includes('guide') || folder.includes('tutorial')) {
category = 'tutorial';
} else if (folder.includes('market') || folder.includes('trend')) {
category = 'industry';
}
// 估算阅读时间(按行数计算)
const readTime = Math.ceil(content.split('\n').length / 20);
articles.push({
id: folder,
category,
title,
excerpt: excerpt.length > 100 ? excerpt.substring(0, 100) + '...' : excerpt,
author: 'CloudPro 技术团队',
date: new Date().toISOString().split('T')[0], // 使用当前日期作为默认值
readTime: Math.max(1, readTime), // 至少1分钟
});
}
}
// 按日期排序(最新的在前)
articles.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
return NextResponse.json(articles);
} catch (error) {
console.error('Error reading articles:', error);
return NextResponse.json([], { status: 500 });
}
}