BE-MiniERP/modules/inventory/handler/colour_handler.go

64 lines
1.7 KiB
Go

package handler
import (
"BE-MiniERP/database"
"BE-MiniERP/modules/inventory/models"
"BE-MiniERP/modules/inventory/repository"
"strconv"
"github.com/gofiber/fiber/v2"
)
type ColourHandler struct {
Repo *repository.ColourRepository
}
func NewColourHandler() *ColourHandler {
return &ColourHandler{
Repo: repository.NewColourRepository(database.DB),
}
}
func (h *ColourHandler) GetAll(c *fiber.Ctx) error {
limit := c.QueryInt("limit", 10) // default 10
offset := c.QueryInt("offset", 0) // default 0
search := c.Query("search", "")
colours, err := h.Repo.FindAll(limit, offset, search)
if err != nil {
return c.Status(500).JSON(fiber.Map{"error": "Failed to fetch colours"})
}
return c.JSON(colours)
}
func (h *ColourHandler) Create(c *fiber.Ctx) error {
var input models.Colour
if err := c.BodyParser(&input); err != nil {
return c.Status(400).JSON(fiber.Map{"error": "Invalid input"})
}
if err := h.Repo.Create(&input); err != nil {
return c.Status(500).JSON(fiber.Map{"error": "Failed to create colour"})
}
return c.JSON(input)
}
func (h *ColourHandler) Update(c *fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
var input models.Colour
if err := c.BodyParser(&input); err != nil {
return c.Status(400).JSON(fiber.Map{"error": "Invalid input"})
}
if err := h.Repo.Update(uint(id), &input); err != nil {
return c.Status(500).JSON(fiber.Map{"error": "Failed to update colour"})
}
return c.JSON(fiber.Map{"message": "Colour updated"})
}
func (h *ColourHandler) Delete(c *fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
if err := h.Repo.Delete(uint(id)); err != nil {
return c.Status(500).JSON(fiber.Map{"error": "Failed to delete colour"})
}
return c.JSON(fiber.Map{"message": "Colour deleted"})
}