import type { FoodItemDto, FoodLibraryResponseDto, GetFoodByIdParams, SearchFoodsParams } from '@/types/food'; import { api } from './api'; export interface CreateCustomFoodDto { name: string; description?: string; caloriesPer100g?: number; proteinPer100g?: number; carbohydratePer100g?: number; fatPer100g?: number; fiberPer100g?: number; sugarPer100g?: number; sodiumPer100g?: number; additionalNutrition?: Record; imageUrl?: string; } /** * 食物库 API 服务 */ export class FoodLibraryApi { private static readonly BASE_PATH = '/food-library'; /** * 获取食物库列表 */ static async getFoodLibrary(): Promise { return api.get(this.BASE_PATH); } /** * 搜索食物 */ static async searchFoods(params: SearchFoodsParams): Promise { const { keyword } = params; if (!keyword || keyword.trim().length === 0) { return []; } const encodedKeyword = encodeURIComponent(keyword.trim()); return api.get(`${this.BASE_PATH}/search?keyword=${encodedKeyword}`); } /** * 根据ID获取食物详情 */ static async getFoodById(params: GetFoodByIdParams): Promise { const { id } = params; return api.get(`${this.BASE_PATH}/${id}`); } /** * 创建自定义食物 */ static async createCustomFood(data: CreateCustomFoodDto): Promise { return api.post(`${this.BASE_PATH}/custom`, data); } /** * 删除自定义食物 */ static async deleteCustomFood(id: number): Promise { return api.delete(`${this.BASE_PATH}/custom/${id}`); } } // 导出便捷方法 export const foodLibraryApi = { getFoodLibrary: () => FoodLibraryApi.getFoodLibrary(), searchFoods: (keyword: string) => FoodLibraryApi.searchFoods({ keyword }), getFoodById: (id: number) => FoodLibraryApi.getFoodById({ id }), createCustomFood: (data: CreateCustomFoodDto) => FoodLibraryApi.createCustomFood(data), deleteCustomFood: (id: number) => FoodLibraryApi.deleteCustomFood(id), };