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:
@@ -6,18 +6,19 @@ 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 } from '@/utils/blog-utils';
|
||||
|
||||
// 使用Astro.currentLocale获取当前语言环境
|
||||
// Get current language environment using Astro.currentLocale
|
||||
const lang = Astro.currentLocale as Lang || defaultLang;
|
||||
|
||||
// 使用Astro.glob读取所有博客文章
|
||||
const allPosts = await Astro.glob('./posts/*.md');
|
||||
// Read all blog posts using import.meta.glob
|
||||
const allPosts = await import.meta.glob('./posts/*.md', { eager: true });
|
||||
|
||||
// 处理博客文章数据
|
||||
const blogPosts: BlogPost[] = allPosts.map((post) => {
|
||||
// Process blog post data
|
||||
const blogPosts: BlogPost[] = Object.values(allPosts).map((post: any) => {
|
||||
const slug = post.url?.split('/').filter(Boolean).pop() || '';
|
||||
|
||||
// 获取文章的默认图片,如果frontmatter中没有指定
|
||||
// Default image if not specified in frontmatter
|
||||
const defaultImage = "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=250&fit=crop&crop=center";
|
||||
|
||||
return {
|
||||
@@ -34,43 +35,8 @@ 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 allCategories = new Set<string>();
|
||||
const allTags = new Set<string>();
|
||||
|
||||
// 收集所有文章的分类和标签
|
||||
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();
|
||||
// Sort posts by date
|
||||
const sortedBlogPosts = sortPostsByDate(blogPosts);
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in New Issue
Block a user