91 lines
2.5 KiB
Go
91 lines
2.5 KiB
Go
package handler
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"soul-api/internal/database"
|
||
"soul-api/internal/model"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// DBVipRolesList GET /api/db/vip-roles 角色列表(管理端 Set VIP 下拉用)
|
||
func DBVipRolesList(c *gin.Context) {
|
||
db := database.DB()
|
||
var roles []model.VipRole
|
||
if err := db.Order("sort ASC, id ASC").Find(&roles).Error; err != nil {
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": err.Error()})
|
||
return
|
||
}
|
||
c.JSON(http.StatusOK, gin.H{"success": true, "data": roles})
|
||
}
|
||
|
||
// DBVipRolesAction POST /api/db/vip-roles 新增角色;PUT 更新;DELETE 删除
|
||
func DBVipRolesAction(c *gin.Context) {
|
||
db := database.DB()
|
||
method := c.Request.Method
|
||
|
||
if method == "POST" {
|
||
var body struct {
|
||
Name string `json:"name" binding:"required"`
|
||
Sort int `json:"sort"`
|
||
}
|
||
if err := c.ShouldBindJSON(&body); err != nil {
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": "name 不能为空"})
|
||
return
|
||
}
|
||
role := model.VipRole{Name: body.Name, Sort: body.Sort}
|
||
if err := db.Create(&role).Error; err != nil {
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": err.Error()})
|
||
return
|
||
}
|
||
c.JSON(http.StatusOK, gin.H{"success": true, "data": role})
|
||
return
|
||
}
|
||
|
||
if method == "PUT" {
|
||
var body struct {
|
||
ID int `json:"id" binding:"required"`
|
||
Name *string `json:"name"`
|
||
Sort *int `json:"sort"`
|
||
}
|
||
if err := c.ShouldBindJSON(&body); err != nil {
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": "id 不能为空"})
|
||
return
|
||
}
|
||
updates := map[string]interface{}{}
|
||
if body.Name != nil {
|
||
updates["name"] = *body.Name
|
||
}
|
||
if body.Sort != nil {
|
||
updates["sort"] = *body.Sort
|
||
}
|
||
if len(updates) == 0 {
|
||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "没有需要更新的字段"})
|
||
return
|
||
}
|
||
if err := db.Model(&model.VipRole{}).Where("id = ?", body.ID).Updates(updates).Error; err != nil {
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": err.Error()})
|
||
return
|
||
}
|
||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "更新成功"})
|
||
return
|
||
}
|
||
|
||
if method == "DELETE" {
|
||
id := c.Query("id")
|
||
if id == "" {
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": "id 不能为空"})
|
||
return
|
||
}
|
||
if err := db.Where("id = ?", id).Delete(&model.VipRole{}).Error; err != nil {
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": err.Error()})
|
||
return
|
||
}
|
||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "删除成功"})
|
||
return
|
||
}
|
||
|
||
c.JSON(http.StatusOK, gin.H{"success": false, "error": "不支持的请求方法"})
|
||
}
|