import api from './api' import { Category } from './queries' // 分类服务 - 处理分类相关的API调用 class CategoryService { private categoryCache: Map = new Map() // 获取所有分类 async getAllCategories(): Promise { if (process.env.NEXT_PUBLIC_USE_REAL_API === 'true') { const response: any = await api.get('/categories?page=1&page_size=100') return response?.categories || [] } else { // Mock API 返回字符串数组,需要转换 const categories: string[] = await api.get('/categories') return categories.map((name: string, index: number) => ({ id: index + 1, name, description: '', created_at: Date.now() / 1000, updated_at: Date.now() / 1000 })) } } // 根据分类ID获取分类名称 async getCategoryName(categoryId: number): Promise { if (this.categoryCache.has(categoryId)) { return this.categoryCache.get(categoryId)! } try { const categories = await this.getAllCategories() // 缓存所有分类 categories.forEach(cat => { this.categoryCache.set(cat.id, cat.name) }) return this.categoryCache.get(categoryId) || 'unknown' } catch (error) { console.error('获取分类名称失败:', error) return 'unknown' } } // 清除缓存 clearCache() { this.categoryCache.clear() } } export const categoryService = new CategoryService()