refactor(blog): extract blog utilities into shared module

Move common blog functionality like post filtering, sorting and data extraction into a centralized utils module.
Replace Astro.glob with import.meta.glob for better performance.
Update all blog components and pages to use the new utilities.
This commit is contained in:
joyzhao
2025-06-19 16:28:59 +08:00
parent 429b13985f
commit 7951121c7f
11 changed files with 609 additions and 695 deletions

View File

@@ -6,15 +6,16 @@ import TagCard from '../../../components/blog/TagCard.astro';
import { type BlogPost } from '@/types';
import { type Lang } from '@/i18n/utils';
import { defaultLang } from '@/i18n/ui';
import { sortPostsByDate, extractCategories, extractTags } from '@/utils/blog-utils';
// 使用Astro.currentLocale获取当前语言环境
const lang = Astro.currentLocale as Lang || defaultLang;
// 使用Astro.glob读取所有中文博客文章
const allPosts = await Astro.glob('./posts/*.md');
// 使用import.meta.glob读取所有中文博客文章
const allPosts = await import.meta.glob('./posts/*.md', { eager: true });
// 处理博客文章数据
const blogPosts: BlogPost[] = allPosts.map((post) => {
const blogPosts: BlogPost[] = Object.values(allPosts).map((post: any) => {
const slug = post.url?.split('/').filter(Boolean).pop() || '';
// 获取文章的默认图片如果frontmatter中没有指定
@@ -34,43 +35,20 @@ const blogPosts: BlogPost[] = allPosts.map((post) => {
};
});
// 按日期排序
const sortedBlogPosts = blogPosts
.filter(post => post.date) // 过滤掉没有日期的文章
.sort((a, b) => {
const dateA = new Date(a.date).getTime();
const dateB = new Date(b.date).getTime();
return dateB - dateA; // 降序排列,最新的文章在前
});
// 使用工具函数按日期排序
const sortedBlogPosts = sortPostsByDate(blogPosts);
// 从博客文章中提取分类和标签
const allCategories = new Set<string>();
const allTags = new Set<string>();
// 提取所有文章的分类和标签信息(用于侧边栏)
const allPostsArray = Object.values(allPosts).map((post: any) => ({
category: post.frontmatter.category || [],
categoryId: post.frontmatter.categoryId || [],
tags: post.frontmatter.tags || [],
tagId: post.frontmatter.tagId || []
}));
// 收集所有文章的分类和标签
allPosts.forEach(post => {
// 处理分类
if (post.frontmatter?.category) {
const categories = Array.isArray(post.frontmatter.category)
? post.frontmatter.category
: [post.frontmatter.category];
categories.forEach(category => {
if (category) allCategories.add(category);
});
}
// 处理标签
if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
post.frontmatter.tags.forEach(tag => {
if (tag) allTags.add(tag);
});
}
});
// 转换为数组并排序
const categories = Array.from(allCategories).sort();
const tags = Array.from(allTags).map(tag => `# ${tag}`).sort();
// 使用工具函数提取分类和标签
const categories = extractCategories(allPostsArray);
const tags = extractTags(allPostsArray);
---