Files
mce/internal/controller/favorite_controller.go

123 lines
3.1 KiB
Go

package controller
import (
"net/http"
"strconv"
"metazone.cc/mce/internal/common"
"github.com/gin-gonic/gin"
)
// FavoriteController 收藏夹 API 控制器
type FavoriteController struct {
svc favoriteUseCase
}
// NewFavoriteController 构造函数
func NewFavoriteController(svc favoriteUseCase) *FavoriteController {
return &FavoriteController{svc: svc}
}
// ListFolders 我的收藏夹列表 GET /api/folders
func (fc *FavoriteController) ListFolders(c *gin.Context) {
uid, _, ok := common.GetGinUser(c)
if !ok {
common.Error(c, http.StatusUnauthorized, "请先登录")
return
}
result, err := fc.svc.ListFolders(uid)
if err != nil {
common.Error(c, http.StatusInternalServerError, "获取收藏夹失败")
return
}
common.Ok(c, result)
}
// CreateFolder 创建收藏夹 POST /api/folders
func (fc *FavoriteController) CreateFolder(c *gin.Context) {
uid, _, ok := common.GetGinUser(c)
if !ok {
common.Error(c, http.StatusUnauthorized, "请先登录")
return
}
var req struct {
Name string `json:"name"`
Description string `json:"description"`
IsPublic bool `json:"is_public"`
}
if err := c.ShouldBindJSON(&req); err != nil {
common.Error(c, http.StatusBadRequest, "参数错误")
return
}
f, err := fc.svc.CreateFolder(uid, req.Name, req.Description, req.IsPublic)
if err != nil {
if err.Error() == "收藏夹名称已存在" || err.Error() == "收藏夹名称不能为空" || err.Error() == "收藏夹名称不能超过 50 个字符" {
common.Error(c, http.StatusBadRequest, err.Error())
return
}
common.Error(c, http.StatusInternalServerError, "创建失败")
return
}
common.OkWithMessage(c, f, "收藏夹创建成功")
}
// UpdateFolder 修改收藏夹 PUT /api/folders/:id
func (fc *FavoriteController) UpdateFolder(c *gin.Context) {
uid, _, ok := common.GetGinUser(c)
if !ok {
common.Error(c, http.StatusUnauthorized, "请先登录")
return
}
folderID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
common.Error(c, http.StatusBadRequest, "无效的收藏夹 ID")
return
}
var req struct {
Name string `json:"name"`
Description string `json:"description"`
IsPublic bool `json:"is_public"`
}
if err := c.ShouldBindJSON(&req); err != nil {
common.Error(c, http.StatusBadRequest, "参数错误")
return
}
if err := fc.svc.UpdateFolder(uid, uint(folderID), req.Name, req.Description, req.IsPublic); err != nil {
common.Error(c, http.StatusBadRequest, err.Error())
return
}
common.OkMessage(c, "收藏夹已更新")
}
// DeleteFolder 删除收藏夹 DELETE /api/folders/:id
func (fc *FavoriteController) DeleteFolder(c *gin.Context) {
uid, _, ok := common.GetGinUser(c)
if !ok {
common.Error(c, http.StatusUnauthorized, "请先登录")
return
}
folderID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
common.Error(c, http.StatusBadRequest, "无效的收藏夹 ID")
return
}
if err := fc.svc.DeleteFolder(uid, uint(folderID)); err != nil {
common.Error(c, http.StatusBadRequest, err.Error())
return
}
common.OkMessage(c, "收藏夹已删除")
}