93 lines
2.2 KiB
Go
93 lines
2.2 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"]["/task"] = new(TaskCreate)
|
|
}
|
|
|
|
type taskCreateBody struct {
|
|
Name string `json:"name"`
|
|
Description *string `json:"description,omitempty"`
|
|
Deadline *int64 `json:"deadline,omitempty"`
|
|
}
|
|
|
|
type taskCreateResponse struct {
|
|
Task db.Task `json:"task"`
|
|
}
|
|
|
|
type TaskCreate struct{}
|
|
|
|
// Authorize implements router.AuthorizedRoute.
|
|
func (t *TaskCreate) Authorize(ctx *router.Context) error {
|
|
return middleware.Authenticated(ctx)
|
|
}
|
|
|
|
// ValidateBody implements router.ValidatedBodyRoute.
|
|
func (t *TaskCreate) ValidateBody(ctx *router.Context) error {
|
|
return middleware.ParseJSONBodyWithValidator[taskCreateBody](
|
|
ctx, t, func(value taskCreateBody) error {
|
|
if len(value.Name) > 64 {
|
|
return ctx.Error(nil, 400, "name too long")
|
|
}
|
|
|
|
if len(value.Name) < 3 {
|
|
return ctx.Error(nil, 400, "name too short")
|
|
}
|
|
|
|
if value.Description != nil {
|
|
description := *value.Description
|
|
|
|
if len(description) > 200 {
|
|
return ctx.Error(nil, 400, "description too long")
|
|
}
|
|
}
|
|
|
|
if value.Deadline != nil {
|
|
deadline := *value.Deadline
|
|
|
|
if deadline < 0 {
|
|
return ctx.Error(nil, 400, "deadline cannot be below 0")
|
|
}
|
|
|
|
if deadline < time.Now().Unix() {
|
|
return ctx.Error(nil, 400, "deadline cannot be in the past")
|
|
}
|
|
}
|
|
|
|
return nil
|
|
},
|
|
)
|
|
}
|
|
|
|
// Handle implements router.Route.
|
|
func (t *TaskCreate) Handle(ctx *router.Context) error {
|
|
user := middleware.User(t, ctx)
|
|
body := middleware.JSONBody[taskCreateBody](t, ctx)
|
|
|
|
task, err := ctx.Query.CreateTask(ctx, db.CreateTaskParams{
|
|
Name: body.Name,
|
|
Description: dbutil.SerializeMaybeString(body.Description),
|
|
CreatedBy: user.ID,
|
|
AssignedTo: user.ID,
|
|
CreatedAt: time.Now().Unix(),
|
|
Deadline: dbutil.SerializeMaybeInt(body.Deadline),
|
|
})
|
|
|
|
if err != nil {
|
|
return ctx.GenericError(err, http.StatusInternalServerError)
|
|
}
|
|
|
|
return ctx.JSON(200, task)
|
|
}
|
|
|
|
var _ router.AuthorizedRoute = new(TaskCreate)
|
|
var _ router.ValidatedBodyRoute = new(TaskCreate)
|