healthapp
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

98 lines
2.6 KiB

package logic
import (
"context"
"healthapi/internal/model"
"healthapi/internal/svc"
"healthapi/internal/types"
"healthapi/pkg/errorx"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateLifestyleLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateLifestyleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLifestyleLogic {
return &UpdateLifestyleLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateLifestyleLogic) UpdateLifestyle(req *types.UpdateLifestyleReq) (resp *types.LifestyleInfo, err error) {
userID, err := GetUserIDFromCtx(l.ctx)
if err != nil {
return nil, errorx.ErrUnauthorized
}
var lifestyle model.LifestyleInfo
if err := l.svcCtx.DB.Where("user_id = ?", userID).First(&lifestyle).Error; err != nil {
lifestyle = model.LifestyleInfo{UserID: userID}
}
// 更新字段
if req.SleepTime != "" {
lifestyle.SleepTime = req.SleepTime
}
if req.WakeTime != "" {
lifestyle.WakeTime = req.WakeTime
}
if req.SleepQuality != "" {
lifestyle.SleepQuality = req.SleepQuality
}
if req.MealRegularity != "" {
lifestyle.MealRegularity = req.MealRegularity
}
if req.DietPreference != "" {
lifestyle.DietPreference = req.DietPreference
}
if req.DailyWaterML > 0 {
lifestyle.DailyWaterML = req.DailyWaterML
}
if req.ExerciseFrequency != "" {
lifestyle.ExerciseFrequency = req.ExerciseFrequency
}
if req.ExerciseType != "" {
lifestyle.ExerciseType = req.ExerciseType
}
if req.ExerciseDurationMin > 0 {
lifestyle.ExerciseDurationMin = req.ExerciseDurationMin
}
lifestyle.IsSmoker = req.IsSmoker
if req.AlcoholFrequency != "" {
lifestyle.AlcoholFrequency = req.AlcoholFrequency
}
// 保存
if lifestyle.ID == 0 {
if err := l.svcCtx.DB.Create(&lifestyle).Error; err != nil {
return nil, errorx.ErrServerError
}
} else {
if err := l.svcCtx.DB.Save(&lifestyle).Error; err != nil {
return nil, errorx.ErrServerError
}
}
return &types.LifestyleInfo{
ID: uint(lifestyle.ID),
UserID: lifestyle.UserID,
SleepTime: lifestyle.SleepTime,
WakeTime: lifestyle.WakeTime,
SleepQuality: lifestyle.SleepQuality,
MealRegularity: lifestyle.MealRegularity,
DietPreference: lifestyle.DietPreference,
DailyWaterML: lifestyle.DailyWaterML,
ExerciseFrequency: lifestyle.ExerciseFrequency,
ExerciseType: lifestyle.ExerciseType,
ExerciseDurationMin: lifestyle.ExerciseDurationMin,
IsSmoker: lifestyle.IsSmoker,
AlcoholFrequency: lifestyle.AlcoholFrequency,
}, nil
}