实现 UpdatePlan 和单测
This commit is contained in:
@@ -220,9 +220,60 @@ func (c *Controller) ListPlans(ctx *gin.Context) {
|
||||
// @Failure 200 {object} controller.Response "业务失败,具体错误码和信息见响应体(例如400, 404, 500)"
|
||||
// @Router /plans/{id} [put]
|
||||
func (c *Controller) UpdatePlan(ctx *gin.Context) {
|
||||
// 占位符:此处应调用服务层或仓库层来更新计划
|
||||
c.logger.Infof("收到更新计划请求 (占位符)")
|
||||
controller.SendResponse(ctx, controller.CodeSuccess, "更新计划接口占位符", PlanResponse{ID: 0, Name: "占位计划"})
|
||||
// 1. 从 URL 路径中获取 ID
|
||||
idStr := ctx.Param("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的计划ID格式")
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 绑定请求体
|
||||
var req UpdatePlanRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
controller.SendErrorResponse(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 3. 将请求转换为模型(转换函数带校验)
|
||||
planToUpdate, err := PlanFromUpdateRequest(&req)
|
||||
if err != nil {
|
||||
controller.SendErrorResponse(ctx, controller.CodeBadRequest, "计划数据校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
planToUpdate.ID = uint(id) // 确保ID被设置
|
||||
|
||||
// 4. 检查计划是否存在
|
||||
_, err = c.planRepo.GetBasicPlanByID(uint(id))
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
controller.SendErrorResponse(ctx, controller.CodeNotFound, "计划不存在")
|
||||
return
|
||||
}
|
||||
c.logger.Errorf("获取计划详情失败: %v", err)
|
||||
controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取计划详情时发生内部错误")
|
||||
return
|
||||
}
|
||||
|
||||
// 5. 调用仓库方法更新计划
|
||||
if err := c.planRepo.UpdatePlan(planToUpdate); err != nil {
|
||||
controller.SendErrorResponse(ctx, controller.CodeBadRequest, "更新计划失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 6. 获取更新后的完整计划用于响应
|
||||
updatedPlan, err := c.planRepo.GetPlanByID(uint(id))
|
||||
if err != nil {
|
||||
c.logger.Errorf("获取更新后的计划详情失败: %v", err)
|
||||
controller.SendErrorResponse(ctx, controller.CodeInternalError, "获取更新后计划详情时发生内部错误")
|
||||
return
|
||||
}
|
||||
|
||||
// 7. 将模型转换为响应 DTO
|
||||
resp := PlanToResponse(updatedPlan)
|
||||
|
||||
// 8. 发送成功响应
|
||||
controller.SendResponse(ctx, controller.CodeSuccess, "计划更新成功", resp)
|
||||
}
|
||||
|
||||
// DeletePlan godoc
|
||||
|
||||
Reference in New Issue
Block a user