diff --git a/internal/photos/api/album.go b/internal/photos/api/album.go index 778f64e..0a15523 100644 --- a/internal/photos/api/album.go +++ b/internal/photos/api/album.go @@ -1 +1,43 @@ package api + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "gitlab.celogeek.com/photos/api/internal/photos/models" + "gopkg.in/validator.v2" +) + +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) + + album := &models.Album{ + Name: req.Name, + ParentId: req.Parent, + AuthorId: &sess.AccountId, + } + + if err := s.DB.Create(album).Error; err != nil { + s.Error(c, http.StatusConflict, err) + return + } + + c.JSON(http.StatusOK, gin.H{ + "status": "success", + "album": album, + }) +} diff --git a/internal/photos/api/main.go b/internal/photos/api/main.go index 1878ee9..50ed71e 100644 --- a/internal/photos/api/main.go +++ b/internal/photos/api/main.go @@ -64,6 +64,10 @@ func (s *Service) SetupRoutes() { }) }) + album := s.Gin.Group("/album") + album.Use(s.RequireSession) + album.POST("/", s.AlbumCreate) + s.Gin.NoRoute(func(c *gin.Context) { s.Error(c, http.StatusNotFound, ErrReqNotFound) }) diff --git a/internal/photos/models/album.go b/internal/photos/models/album.go index 0acc779..83f623d 100644 --- a/internal/photos/models/album.go +++ b/internal/photos/models/album.go @@ -6,9 +6,9 @@ type Album struct { ID uint32 `gorm:"primary_key"` Name string `gorm:"not null"` Parent *Album `gorm:"constraint:OnDelete:SET NULL,OnUpdate:CASCADE"` - ParentId uint32 + ParentId *uint32 Author *Account `gorm:"constraint:OnDelete:SET NULL,OnUpdate:CASCADE"` - AuthorId uint32 + AuthorId *uint32 Photos []*Photo `gorm:"many2many:album_photos"` CreatedAt time.Time UpdatedAt time.Time