76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package routes
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.red-panda.pet/pandaware/house/backend/db"
|
|
"git.red-panda.pet/pandaware/house/backend/dbutil"
|
|
"git.red-panda.pet/pandaware/house/backend/middleware"
|
|
"git.red-panda.pet/pandaware/house/backend/router"
|
|
)
|
|
|
|
func init() {
|
|
routes["POST"]["/category"] = new(CategoryCreate)
|
|
}
|
|
|
|
type categoryCreateBody struct {
|
|
Name string `json:"name"`
|
|
Description *string `json:"description"`
|
|
}
|
|
|
|
type categoryCreateResponse struct {
|
|
Category db.Category `json:"category"`
|
|
}
|
|
|
|
type CategoryCreate struct{}
|
|
|
|
// ValidateBody implements router.ValidatedBodyRoute.
|
|
func (c *CategoryCreate) ValidateBody(ctx *router.Context) error {
|
|
return middleware.ParseJSONBodyWithValidator(
|
|
ctx, c, func(value categoryCreateBody) error {
|
|
if len(value.Name) < 5 {
|
|
return ctx.Error(nil, 400, "Name too short")
|
|
}
|
|
|
|
if value.Description != nil {
|
|
description := *value.Description
|
|
|
|
if len(description) > 100 {
|
|
return ctx.Error(nil, 400, "Description too long")
|
|
}
|
|
}
|
|
|
|
return nil
|
|
},
|
|
)
|
|
}
|
|
|
|
// Authorize implements router.AuthorizedRoute.
|
|
func (c *CategoryCreate) Authorize(ctx *router.Context) error {
|
|
return middleware.Authenticated(ctx)
|
|
}
|
|
|
|
// Handle implements router.Route.
|
|
func (c *CategoryCreate) Handle(ctx *router.Context) error {
|
|
user := middleware.User(c, ctx)
|
|
body := middleware.JSONBody[categoryCreateBody](c, ctx)
|
|
|
|
category, err := ctx.Query.CreateCategory(ctx, db.CreateCategoryParams{
|
|
Name: body.Name,
|
|
Description: dbutil.SerializeMaybeString(body.Description),
|
|
CreatedBy: user.ID,
|
|
CreatedAt: time.Now().Unix(),
|
|
})
|
|
|
|
if err != nil {
|
|
return ctx.GenericError(err, http.StatusInternalServerError)
|
|
}
|
|
|
|
return ctx.JSON(200, categoryCreateResponse{
|
|
Category: category,
|
|
})
|
|
}
|
|
|
|
var _ router.AuthorizedRoute = new(CategoryCreate)
|
|
var _ router.ValidatedBodyRoute = new(CategoryCreate)
|