Interactive/pkg/server/categories_api.go

90 lines
2.3 KiB
Go
Raw Normal View History

2024-02-14 14:03:45 +00:00
package server
import (
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
"github.com/gofiber/fiber/v2"
)
2024-03-02 17:23:11 +00:00
func listCategories(c *fiber.Ctx) error {
2024-02-14 14:03:45 +00:00
categories, err := services.ListCategory()
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
return c.JSON(categories)
}
func newCategory(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
if user.PowerLevel <= 55 {
return fiber.NewError(fiber.StatusForbidden, "require power level 55 to create categories")
}
var data struct {
Alias string `json:"alias" validate:"required"`
Name string `json:"name" validate:"required"`
Description string `json:"description"`
}
if err := BindAndValidate(c, &data); err != nil {
return err
}
category, err := services.NewCategory(data.Alias, data.Name, data.Description)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
return c.JSON(category)
}
func editCategory(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
if user.PowerLevel <= 55 {
return fiber.NewError(fiber.StatusForbidden, "require power level 55 to edit categories")
}
id, _ := c.ParamsInt("categoryId", 0)
category, err := services.GetCategoryWithID(uint(id))
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
var data struct {
Alias string `json:"alias" validate:"required"`
Name string `json:"name" validate:"required"`
Description string `json:"description"`
}
if err := BindAndValidate(c, &data); err != nil {
return err
}
category, err = services.EditCategory(category, data.Alias, data.Name, data.Description)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
return c.JSON(category)
}
func deleteCategory(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
if user.PowerLevel <= 55 {
return fiber.NewError(fiber.StatusForbidden, "require power level 55 to delete categories")
}
id, _ := c.ParamsInt("categoryId", 0)
category, err := services.GetCategoryWithID(uint(id))
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if err := services.DeleteCategory(category); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
return c.JSON(category)
}