67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gitlab.celogeek.com/photos/api/internal/photos/models"
|
|
"gopkg.in/validator.v2"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
type AlbumCreateRequest struct {
|
|
Name string `validate:"min=1,max=255,regexp=^[^/]*$"`
|
|
Parent *uint32
|
|
}
|
|
|
|
func (s *Service) AlbumCreate(c *gin.Context) {
|
|
req := &AlbumCreateRequest{}
|
|
if err := c.ShouldBindJSON(req); err != nil {
|
|
s.Error(c, http.StatusBadRequest, err)
|
|
}
|
|
if err := validator.Validate(req); err != nil {
|
|
s.Error(c, http.StatusExpectationFailed, err)
|
|
return
|
|
}
|
|
|
|
sess := s.CurrentSession(c)
|
|
|
|
var parentAlbum *models.Album
|
|
|
|
if req.Parent != nil {
|
|
parentAlbum = &models.Album{}
|
|
if err := s.
|
|
DB.
|
|
Debug().
|
|
Preload("Author").
|
|
Find(parentAlbum, req.Parent).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
s.Error(c, http.StatusNotFound, ErrAlbumDontExists)
|
|
} else {
|
|
s.Error(c, http.StatusInternalServerError, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
album := &models.Album{
|
|
Name: req.Name,
|
|
Parent: parentAlbum,
|
|
ParentId: req.Parent,
|
|
Author: sess.Account,
|
|
AuthorId: &sess.Account.ID,
|
|
}
|
|
|
|
if err := s.DB.Debug().Omit(clause.Associations).Clauses(clause.Returning{}).Create(album).Error; err != nil {
|
|
s.Error(c, http.StatusConflict, err)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"status": "success",
|
|
"album": album,
|
|
})
|
|
}
|