feat: 添加种子数据初始化功能,重构多个处理程序以简化错误响应和用户验证

This commit is contained in:
lan
2025-12-02 10:33:19 +08:00
parent bdd2be5dc5
commit 10fdcd916b
30 changed files with 1291 additions and 1778 deletions

View File

@@ -8,7 +8,6 @@ import (
"carrotskin/pkg/database"
"carrotskin/pkg/logger"
"carrotskin/pkg/storage"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
@@ -27,59 +26,44 @@ import (
// @Failure 400 {object} model.ErrorResponse "请求参数错误"
// @Router /api/v1/texture/upload-url [post]
func GenerateTextureUploadURL(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
userID, ok := GetUserIDFromContext(c)
if !ok {
return
}
var req types.GenerateTextureUploadURLRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"请求参数错误",
err,
))
RespondBadRequest(c, "请求参数错误", err)
return
}
// 调用UploadService生成预签名URL
storageClient := storage.MustGetClient()
cfg := *config.MustGetRustFSConfig()
result, err := service.GenerateTextureUploadURL(
c.Request.Context(),
storageClient,
cfg,
userID.(int64),
userID,
req.FileName,
string(req.TextureType),
)
if err != nil {
logger.MustGetLogger().Error("生成材质上传URL失败",
zap.Int64("user_id", userID.(int64)),
zap.Int64("user_id", userID),
zap.String("file_name", req.FileName),
zap.String("texture_type", string(req.TextureType)),
zap.Error(err),
)
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
err.Error(),
nil,
))
RespondBadRequest(c, err.Error(), nil)
return
}
// 返回响应
c.JSON(http.StatusOK, model.NewSuccessResponse(&types.GenerateTextureUploadURLResponse{
RespondSuccess(c, &types.GenerateTextureUploadURLResponse{
PostURL: result.PostURL,
FormData: result.FormData,
TextureURL: result.FileURL,
ExpiresIn: 900, // 15分钟 = 900秒
}))
ExpiresIn: 900,
})
}
// CreateTexture 创建材质记录
@@ -94,40 +78,25 @@ func GenerateTextureUploadURL(c *gin.Context) {
// @Failure 400 {object} model.ErrorResponse "请求参数错误"
// @Router /api/v1/texture [post]
func CreateTexture(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
userID, ok := GetUserIDFromContext(c)
if !ok {
return
}
var req types.CreateTextureRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"请求参数错误",
err,
))
RespondBadRequest(c, "请求参数错误", err)
return
}
// TODO: 从配置或数据库读取限制
maxTextures := 100
if err := service.CheckTextureUploadLimit(database.MustGetDB(), userID.(int64), maxTextures); err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
err.Error(),
nil,
))
maxTextures := service.GetMaxTexturesPerUser()
if err := service.CheckTextureUploadLimit(database.MustGetDB(), userID, maxTextures); err != nil {
RespondBadRequest(c, err.Error(), nil)
return
}
// 创建材质
texture, err := service.CreateTexture(database.MustGetDB(),
userID.(int64),
userID,
req.Name,
req.Description,
string(req.Type),
@@ -139,36 +108,15 @@ func CreateTexture(c *gin.Context) {
)
if err != nil {
logger.MustGetLogger().Error("创建材质失败",
zap.Int64("user_id", userID.(int64)),
zap.Int64("user_id", userID),
zap.String("name", req.Name),
zap.Error(err),
)
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
err.Error(),
nil,
))
RespondBadRequest(c, err.Error(), nil)
return
}
// 返回响应
c.JSON(http.StatusOK, model.NewSuccessResponse(&types.TextureInfo{
ID: texture.ID,
UploaderID: texture.UploaderID,
Name: texture.Name,
Description: texture.Description,
Type: types.TextureType(texture.Type),
URL: texture.URL,
Hash: texture.Hash,
Size: texture.Size,
IsPublic: texture.IsPublic,
DownloadCount: texture.DownloadCount,
FavoriteCount: texture.FavoriteCount,
IsSlim: texture.IsSlim,
Status: texture.Status,
CreatedAt: texture.CreatedAt,
UpdatedAt: texture.UpdatedAt,
}))
RespondSuccess(c, TextureToTextureInfo(texture))
}
// GetTexture 获取材质详情
@@ -182,44 +130,19 @@ func CreateTexture(c *gin.Context) {
// @Failure 404 {object} model.ErrorResponse "材质不存在"
// @Router /api/v1/texture/{id} [get]
func GetTexture(c *gin.Context) {
idStr := c.Param("id")
id, err := strconv.ParseInt(idStr, 10, 64)
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"无效的材质ID",
err,
))
RespondBadRequest(c, "无效的材质ID", err)
return
}
texture, err := service.GetTextureByID(database.MustGetDB(), id)
if err != nil {
c.JSON(http.StatusNotFound, model.NewErrorResponse(
model.CodeNotFound,
err.Error(),
nil,
))
RespondNotFound(c, err.Error())
return
}
c.JSON(http.StatusOK, model.NewSuccessResponse(&types.TextureInfo{
ID: texture.ID,
UploaderID: texture.UploaderID,
Name: texture.Name,
Description: texture.Description,
Type: types.TextureType(texture.Type),
URL: texture.URL,
Hash: texture.Hash,
Size: texture.Size,
IsPublic: texture.IsPublic,
DownloadCount: texture.DownloadCount,
FavoriteCount: texture.FavoriteCount,
IsSlim: texture.IsSlim,
Status: texture.Status,
CreatedAt: texture.CreatedAt,
UpdatedAt: texture.UpdatedAt,
}))
RespondSuccess(c, TextureToTextureInfo(texture))
}
// SearchTextures 搜索材质
@@ -253,41 +176,12 @@ func SearchTextures(c *gin.Context) {
textures, total, err := service.SearchTextures(database.MustGetDB(), keyword, textureType, publicOnly, page, pageSize)
if err != nil {
logger.MustGetLogger().Error("搜索材质失败",
zap.String("keyword", keyword),
zap.Error(err),
)
c.JSON(http.StatusInternalServerError, model.NewErrorResponse(
model.CodeServerError,
"搜索材质失败",
err,
))
logger.MustGetLogger().Error("搜索材质失败", zap.String("keyword", keyword), zap.Error(err))
RespondServerError(c, "搜索材质失败", err)
return
}
// 转换为TextureInfo
textureInfos := make([]*types.TextureInfo, len(textures))
for i, texture := range textures {
textureInfos[i] = &types.TextureInfo{
ID: texture.ID,
UploaderID: texture.UploaderID,
Name: texture.Name,
Description: texture.Description,
Type: types.TextureType(texture.Type),
URL: texture.URL,
Hash: texture.Hash,
Size: texture.Size,
IsPublic: texture.IsPublic,
DownloadCount: texture.DownloadCount,
FavoriteCount: texture.FavoriteCount,
IsSlim: texture.IsSlim,
Status: texture.Status,
CreatedAt: texture.CreatedAt,
UpdatedAt: texture.UpdatedAt,
}
}
c.JSON(http.StatusOK, model.NewPaginationResponse(textureInfos, total, page, pageSize))
c.JSON(200, model.NewPaginationResponse(TexturesToTextureInfos(textures), total, page, pageSize))
}
// UpdateTexture 更新材质
@@ -303,69 +197,35 @@ func SearchTextures(c *gin.Context) {
// @Failure 403 {object} model.ErrorResponse "无权操作"
// @Router /api/v1/texture/{id} [put]
func UpdateTexture(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
userID, ok := GetUserIDFromContext(c)
if !ok {
return
}
idStr := c.Param("id")
textureID, err := strconv.ParseInt(idStr, 10, 64)
textureID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"无效的材质ID",
err,
))
RespondBadRequest(c, "无效的材质ID", err)
return
}
var req types.UpdateTextureRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"请求参数错误",
err,
))
RespondBadRequest(c, "请求参数错误", err)
return
}
texture, err := service.UpdateTexture(database.MustGetDB(), textureID, userID.(int64), req.Name, req.Description, req.IsPublic)
texture, err := service.UpdateTexture(database.MustGetDB(), textureID, userID, req.Name, req.Description, req.IsPublic)
if err != nil {
logger.MustGetLogger().Error("更新材质失败",
zap.Int64("user_id", userID.(int64)),
zap.Int64("user_id", userID),
zap.Int64("texture_id", textureID),
zap.Error(err),
)
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
err.Error(),
nil,
))
RespondForbidden(c, err.Error())
return
}
c.JSON(http.StatusOK, model.NewSuccessResponse(&types.TextureInfo{
ID: texture.ID,
UploaderID: texture.UploaderID,
Name: texture.Name,
Description: texture.Description,
Type: types.TextureType(texture.Type),
URL: texture.URL,
Hash: texture.Hash,
Size: texture.Size,
IsPublic: texture.IsPublic,
DownloadCount: texture.DownloadCount,
FavoriteCount: texture.FavoriteCount,
IsSlim: texture.IsSlim,
Status: texture.Status,
CreatedAt: texture.CreatedAt,
UpdatedAt: texture.UpdatedAt,
}))
RespondSuccess(c, TextureToTextureInfo(texture))
}
// DeleteTexture 删除材质
@@ -380,42 +240,28 @@ func UpdateTexture(c *gin.Context) {
// @Failure 403 {object} model.ErrorResponse "无权操作"
// @Router /api/v1/texture/{id} [delete]
func DeleteTexture(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
userID, ok := GetUserIDFromContext(c)
if !ok {
return
}
idStr := c.Param("id")
textureID, err := strconv.ParseInt(idStr, 10, 64)
textureID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"无效的材质ID",
err,
))
RespondBadRequest(c, "无效的材质ID", err)
return
}
if err := service.DeleteTexture(database.MustGetDB(), textureID, userID.(int64)); err != nil {
if err := service.DeleteTexture(database.MustGetDB(), textureID, userID); err != nil {
logger.MustGetLogger().Error("删除材质失败",
zap.Int64("user_id", userID.(int64)),
zap.Int64("user_id", userID),
zap.Int64("texture_id", textureID),
zap.Error(err),
)
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
err.Error(),
nil,
))
RespondForbidden(c, err.Error())
return
}
c.JSON(http.StatusOK, model.NewSuccessResponse(nil))
RespondSuccess(c, nil)
}
// ToggleFavorite 切换收藏状态
@@ -429,45 +275,29 @@ func DeleteTexture(c *gin.Context) {
// @Success 200 {object} model.Response "切换成功"
// @Router /api/v1/texture/{id}/favorite [post]
func ToggleFavorite(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
userID, ok := GetUserIDFromContext(c)
if !ok {
return
}
idStr := c.Param("id")
textureID, err := strconv.ParseInt(idStr, 10, 64)
textureID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"无效的材质ID",
err,
))
RespondBadRequest(c, "无效的材质ID", err)
return
}
isFavorited, err := service.ToggleTextureFavorite(database.MustGetDB(), userID.(int64), textureID)
isFavorited, err := service.ToggleTextureFavorite(database.MustGetDB(), userID, textureID)
if err != nil {
logger.MustGetLogger().Error("切换收藏状态失败",
zap.Int64("user_id", userID.(int64)),
zap.Int64("user_id", userID),
zap.Int64("texture_id", textureID),
zap.Error(err),
)
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
err.Error(),
nil,
))
RespondBadRequest(c, err.Error(), nil)
return
}
c.JSON(http.StatusOK, model.NewSuccessResponse(map[string]bool{
"is_favorited": isFavorited,
}))
RespondSuccess(c, map[string]bool{"is_favorited": isFavorited})
}
// GetUserTextures 获取用户上传的材质列表
@@ -482,56 +312,22 @@ func ToggleFavorite(c *gin.Context) {
// @Success 200 {object} model.PaginationResponse "获取成功"
// @Router /api/v1/texture/my [get]
func GetUserTextures(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
userID, ok := GetUserIDFromContext(c)
if !ok {
return
}
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
textures, total, err := service.GetUserTextures(database.MustGetDB(), userID.(int64), page, pageSize)
textures, total, err := service.GetUserTextures(database.MustGetDB(), userID, page, pageSize)
if err != nil {
logger.MustGetLogger().Error("获取用户材质列表失败",
zap.Int64("user_id", userID.(int64)),
zap.Error(err),
)
c.JSON(http.StatusInternalServerError, model.NewErrorResponse(
model.CodeServerError,
"获取材质列表失败",
err,
))
logger.MustGetLogger().Error("获取用户材质列表失败", zap.Int64("user_id", userID), zap.Error(err))
RespondServerError(c, "获取材质列表失败", err)
return
}
// 转换为TextureInfo
textureInfos := make([]*types.TextureInfo, len(textures))
for i, texture := range textures {
textureInfos[i] = &types.TextureInfo{
ID: texture.ID,
UploaderID: texture.UploaderID,
Name: texture.Name,
Description: texture.Description,
Type: types.TextureType(texture.Type),
URL: texture.URL,
Hash: texture.Hash,
Size: texture.Size,
IsPublic: texture.IsPublic,
DownloadCount: texture.DownloadCount,
FavoriteCount: texture.FavoriteCount,
IsSlim: texture.IsSlim,
Status: texture.Status,
CreatedAt: texture.CreatedAt,
UpdatedAt: texture.UpdatedAt,
}
}
c.JSON(http.StatusOK, model.NewPaginationResponse(textureInfos, total, page, pageSize))
c.JSON(200, model.NewPaginationResponse(TexturesToTextureInfos(textures), total, page, pageSize))
}
// GetUserFavorites 获取用户收藏的材质列表
@@ -546,54 +342,20 @@ func GetUserTextures(c *gin.Context) {
// @Success 200 {object} model.PaginationResponse "获取成功"
// @Router /api/v1/texture/favorites [get]
func GetUserFavorites(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
userID, ok := GetUserIDFromContext(c)
if !ok {
return
}
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
textures, total, err := service.GetUserTextureFavorites(database.MustGetDB(), userID.(int64), page, pageSize)
textures, total, err := service.GetUserTextureFavorites(database.MustGetDB(), userID, page, pageSize)
if err != nil {
logger.MustGetLogger().Error("获取用户收藏列表失败",
zap.Int64("user_id", userID.(int64)),
zap.Error(err),
)
c.JSON(http.StatusInternalServerError, model.NewErrorResponse(
model.CodeServerError,
"获取收藏列表失败",
err,
))
logger.MustGetLogger().Error("获取用户收藏列表失败", zap.Int64("user_id", userID), zap.Error(err))
RespondServerError(c, "获取收藏列表失败", err)
return
}
// 转换为TextureInfo
textureInfos := make([]*types.TextureInfo, len(textures))
for i, texture := range textures {
textureInfos[i] = &types.TextureInfo{
ID: texture.ID,
UploaderID: texture.UploaderID,
Name: texture.Name,
Description: texture.Description,
Type: types.TextureType(texture.Type),
URL: texture.URL,
Hash: texture.Hash,
Size: texture.Size,
IsPublic: texture.IsPublic,
DownloadCount: texture.DownloadCount,
FavoriteCount: texture.FavoriteCount,
IsSlim: texture.IsSlim,
Status: texture.Status,
CreatedAt: texture.CreatedAt,
UpdatedAt: texture.UpdatedAt,
}
}
c.JSON(http.StatusOK, model.NewPaginationResponse(textureInfos, total, page, pageSize))
c.JSON(200, model.NewPaginationResponse(TexturesToTextureInfos(textures), total, page, pageSize))
}