refactor(产品服务): 重构产品数据格式化逻辑,直接返回字典对象

将品牌/口味/规格等属性从返回标题改为直接返回完整的 DictItem 对象
保留原 attributes 列表以便前端灵活使用
This commit is contained in:
tikkhun 2025-11-28 16:58:53 +08:00
parent 366fd93dde
commit bc575840b2
1 changed files with 17 additions and 9 deletions

View File

@ -174,28 +174,36 @@ export class ProductService {
return map; return map;
}, {}); }, {});
// 格式化返回的数据 // 格式化返回的数据(中文注释:将品牌/口味/规格/尺寸均以 DictItem 对象形式返回,并保留 attributes 列表)
const formattedItems = items.map(product => { const formattedItems = items.map(product => {
const getAttributeTitle = (dictName: string) => // 函数(中文注释:按字典名称获取对应的属性对象)
product.attributes.find(a => a.dict.name === dictName)?.title || null; const getAttributeByDict = (dictName: string) =>
product.attributes.find(a => a.dict?.name === dictName) || null;
// 条件判断(中文注释:从属性中取出各类维度对象)
const brand = getAttributeByDict('brand');
const flavors = getAttributeByDict('flavor');
const strength = getAttributeByDict('strength');
const size = getAttributeByDict('size');
return { return {
id: product.id, id: product.id,
name: product.name, name: product.name,
nameCn: product.nameCn, nameCn: product.nameCn,
description: product.description, description: product.description,
humidity: getAttributeTitle('humidity'),
sku: product.sku, sku: product.sku,
stock: stockMap[product.sku] || 0, // 使用映射的库存或默认为 0 stock: stockMap[product.sku] || 0, // 中文注释:库存使用聚合库存值
price: product.price, price: product.price,
promotionPrice: product.promotionPrice, promotionPrice: product.promotionPrice,
source: product.source, // 中文注释:补充返回产品来源字段 source: product.source, // 中文注释:返回产品来源字段
createdAt: product.createdAt, createdAt: product.createdAt,
updatedAt: product.updatedAt, updatedAt: product.updatedAt,
// 单列属性(中文注释:直接返回 DictItem 对象,方便前端展示与使用)
brand,
flavors,
strength,
size,
// 全量属性列表(中文注释:保留原 attributes包含字典关系
attributes: product.attributes, attributes: product.attributes,
brandName: getAttributeTitle('brand'),
flavorsName: getAttributeTitle('flavor'),
strengthName: getAttributeTitle('strength'),
}; };
}); });