Files
digital-pilates/services/foodLibraryApi.ts

79 lines
2.1 KiB
TypeScript

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<string, any>;
imageUrl?: string;
}
/**
* 食物库 API 服务
*/
export class FoodLibraryApi {
private static readonly BASE_PATH = '/food-library';
/**
* 获取食物库列表
*/
static async getFoodLibrary(): Promise<FoodLibraryResponseDto> {
return api.get<FoodLibraryResponseDto>(this.BASE_PATH);
}
/**
* 搜索食物
*/
static async searchFoods(params: SearchFoodsParams): Promise<FoodItemDto[]> {
const { keyword } = params;
if (!keyword || keyword.trim().length === 0) {
return [];
}
const encodedKeyword = encodeURIComponent(keyword.trim());
return api.get<FoodItemDto[]>(`${this.BASE_PATH}/search?keyword=${encodedKeyword}`);
}
/**
* 根据ID获取食物详情
*/
static async getFoodById(params: GetFoodByIdParams): Promise<FoodItemDto> {
const { id } = params;
return api.get<FoodItemDto>(`${this.BASE_PATH}/${id}`);
}
/**
* 创建自定义食物
*/
static async createCustomFood(data: CreateCustomFoodDto): Promise<FoodItemDto> {
return api.post<FoodItemDto>(`${this.BASE_PATH}/custom`, data);
}
/**
* 删除自定义食物
*/
static async deleteCustomFood(id: number): Promise<void> {
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),
};