refactor(api): simplify request body parsing in ampcode handlers

This commit is contained in:
hkfires
2025-12-08 14:45:35 +08:00
parent 93a6e2d920
commit 05cfa16e5f
3 changed files with 53 additions and 33 deletions

View File

@@ -785,12 +785,8 @@ func (h *Handler) PutAmpModelMappings(c *gin.Context) {
Value []config.AmpModelMapping `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil {
var mappings []config.AmpModelMapping
if err2 := c.ShouldBindJSON(&mappings); err2 != nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
body.Value = mappings
c.JSON(400, gin.H{"error": "invalid body"})
return
}
h.cfg.AmpCode.ModelMappings = body.Value
h.persist(c)
@@ -802,12 +798,8 @@ func (h *Handler) PatchAmpModelMappings(c *gin.Context) {
Value []config.AmpModelMapping `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil {
var mappings []config.AmpModelMapping
if err2 := c.ShouldBindJSON(&mappings); err2 != nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
body.Value = mappings
c.JSON(400, gin.H{"error": "invalid body"})
return
}
existing := make(map[string]int)
@@ -832,17 +824,7 @@ func (h *Handler) DeleteAmpModelMappings(c *gin.Context) {
var body struct {
Value []string `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil {
var fromList []string
if err2 := c.ShouldBindJSON(&fromList); err2 != nil {
h.cfg.AmpCode.ModelMappings = nil
h.persist(c)
return
}
body.Value = fromList
}
if len(body.Value) == 0 {
if err := c.ShouldBindJSON(&body); err != nil || len(body.Value) == 0 {
h.cfg.AmpCode.ModelMappings = nil
h.persist(c)
return

View File

@@ -240,16 +240,6 @@ func (h *Handler) updateBoolField(c *gin.Context, set func(bool)) {
Value *bool `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
var m map[string]any
if err2 := c.ShouldBindJSON(&m); err2 == nil {
for _, v := range m {
if b, ok := v.(bool); ok {
set(b)
h.persist(c)
return
}
}
}
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}