Files
HouseholdBudgetBook/backend/api/lifecycle.go
T

74 lines
1.8 KiB
Go

package api
import (
"net/http"
"household-book/model"
"household-book/service"
"github.com/gin-gonic/gin"
)
type LifecycleHandler struct{ svc *service.LifecycleService }
func NewLifecycleHandler(svc *service.LifecycleService) *LifecycleHandler {
return &LifecycleHandler{svc: svc}
}
func (h *LifecycleHandler) List(c *gin.Context) {
items, err := h.svc.List(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取人生周期失败"})
return
}
c.JSON(http.StatusOK, items)
}
func (h *LifecycleHandler) Create(c *gin.Context) {
var req model.CreateLifecycleEventRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
if req.Year < 1900 || req.Event == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "年份和事件不能为空"})
return
}
item, err := h.svc.Create(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加事件失败"})
return
}
c.JSON(http.StatusCreated, item)
}
func (h *LifecycleHandler) Update(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req model.UpdateLifecycleEventRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
item, err := h.svc.Update(c.Request.Context(), id, req)
if err != nil {
writeEntityError(c, err, "更新事件失败", "事件不存在")
return
}
c.JSON(http.StatusOK, item)
}
func (h *LifecycleHandler) Delete(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
writeEntityError(c, err, "删除事件失败", "事件不存在")
return
}
c.Status(http.StatusNoContent)
}