支持预设原料和营养简介
This commit is contained in:
@@ -52,7 +52,7 @@ func SeedFromPreset(ctx context.Context, db *gorm.DB, presetDir string) error {
|
||||
|
||||
dataType := gjson.GetBytes(jsonData, "type")
|
||||
if !dataType.Exists() {
|
||||
logger.Warnf("警告: 文件 '%s' 中缺少 'type' 字段,已跳过\n", filePath)
|
||||
logger.Warnf("警告: 文件 '%s' 中缺少 'type' 字段,已跳过", filePath)
|
||||
continue
|
||||
}
|
||||
dataTypeStr := dataType.String()
|
||||
@@ -67,7 +67,7 @@ func SeedFromPreset(ctx context.Context, db *gorm.DB, presetDir string) error {
|
||||
case "nutrient":
|
||||
seederFunc = seedNutrients
|
||||
default:
|
||||
logger.Warnf("警告: 文件 '%s' 中存在未知的 type: '%s',已跳过\n", filePath, dataTypeStr)
|
||||
logger.Warnf("警告: 文件 '%s' 中存在未知的 type: '%s',已跳过", filePath, dataTypeStr)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -100,16 +100,44 @@ func seedNutrients(tx *gorm.DB, jsonData []byte) error {
|
||||
return fmt.Errorf("JSON源文件校验失败: %w", err)
|
||||
}
|
||||
|
||||
// 2. 将通过校验的、干净的数据写入数据库
|
||||
// 2. 解析简介信息
|
||||
descriptionsNode := gjson.GetBytes(jsonData, "descriptions")
|
||||
rawMaterialDescriptions := make(map[string]string)
|
||||
nutrientDescriptions := make(map[string]string)
|
||||
|
||||
if descriptionsNode.Exists() {
|
||||
descriptionsNode.Get("raw_materials").ForEach(func(key, value gjson.Result) bool {
|
||||
rawMaterialDescriptions[key.String()] = value.String()
|
||||
return true
|
||||
})
|
||||
descriptionsNode.Get("nutrients").ForEach(func(key, value gjson.Result) bool {
|
||||
nutrientDescriptions[key.String()] = value.String()
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 将通过校验的、干净的数据写入数据库
|
||||
for rawMaterialName, nutrients := range parsedData {
|
||||
var rawMaterial models.RawMaterial
|
||||
if err := tx.Where(models.RawMaterial{Name: rawMaterialName}).FirstOrCreate(&rawMaterial).Error; err != nil {
|
||||
// 将 Description 放入 Create 对象中
|
||||
err := tx.Where(models.RawMaterial{Name: rawMaterialName}).
|
||||
FirstOrCreate(&rawMaterial, models.RawMaterial{
|
||||
Name: rawMaterialName,
|
||||
Description: rawMaterialDescriptions[rawMaterialName],
|
||||
}).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("预设原料 '%s' 失败: %w", rawMaterialName, err)
|
||||
}
|
||||
|
||||
for nutrientName, value := range nutrients {
|
||||
var nutrient models.Nutrient
|
||||
if err := tx.Where(models.Nutrient{Name: nutrientName}).FirstOrCreate(&nutrient).Error; err != nil {
|
||||
// 将 Description 放入 Create 对象中
|
||||
err := tx.Where(models.Nutrient{Name: nutrientName}).
|
||||
FirstOrCreate(&nutrient, models.Nutrient{
|
||||
Name: nutrientName,
|
||||
Description: nutrientDescriptions[nutrientName],
|
||||
}).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("预设营养素 '%s' 失败: %w", nutrientName, err)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user