TechCorp/lib/news.ts
2025-09-16 17:40:37 +08:00

91 lines
2.5 KiB
TypeScript

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
const newsDirectory = path.join(process.cwd(), 'content/news');
export interface NewsItem {
id: string;
title: string;
title_zh_CN: string;
title_zh_TW: string;
summary: string;
summary_zh_CN: string;
summary_zh_TW: string;
category: string;
date: string;
readTime: string;
tags: string[];
tags_zh_CN: string[];
tags_zh_TW: string[];
author: string;
author_zh_CN: string;
author_zh_TW: string;
image: string;
content: string;
}
export function getAllNews(): NewsItem[] {
const fileNames = fs.readdirSync(newsDirectory);
const allNewsData = fileNames
.filter((fileName) => fileName.endsWith('.md'))
.map((fileName) => {
const id = fileName.replace(/\.md$/, '');
const fullPath = path.join(newsDirectory, fileName);
const fileContents = fs.readFileSync(fullPath, 'utf8');
const matterResult = matter(fileContents);
return {
id,
content: matterResult.content,
...matterResult.data,
} as NewsItem;
});
return allNewsData.sort((a, b) => {
if (a.date < b.date) {
return 1;
} else {
return -1;
}
});
}
export function getNewsById(id: string): NewsItem | undefined {
const allNews = getAllNews();
return allNews.find((news) => news.id === id);
}
// 简单的 markdown 解析器,用于提取特定语言的内容
export function parseMarkdownContent(content: string, language: string): string {
const sections = content.split(/^## (en|zh-CN|zh-TW)$/m);
// 如果没有语言分节,返回原内容
if (sections.length === 1) {
return content;
}
// 查找对应语言的内容
for (let i = 1; i < sections.length; i += 2) {
const sectionLang = sections[i];
const sectionContent = sections[i + 1];
if (sectionLang === language) {
return sectionContent.trim();
}
}
// 如果没找到对应语言,返回英文内容或第一个内容
for (let i = 1; i < sections.length; i += 2) {
const sectionLang = sections[i];
const sectionContent = sections[i + 1];
if (sectionLang === 'en') {
return sectionContent.trim();
}
}
// 如果都没有,返回第一个可用的内容
return sections[2] ? sections[2].trim() : content;
}