bill-server-go/internal/bill/middleware.go
2023-06-12 19:57:57 +08:00

58 lines
1.3 KiB
Go

package bill
import (
"context"
"github.com/gofiber/fiber/v2"
"gopkg.in/go-playground/validator.v9"
)
var validate = validator.New()
func (h *BillHandler) checkGetBillsParamsMiddleware(c *fiber.Ctx) error {
year, _ := c.ParamsInt("year", 0)
month, _ := c.ParamsInt("month", 0)
day, _ := c.ParamsInt("day", 0)
date := BDate{year, month, day}
err := validate.Struct(date)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(&fiber.Map{
"status": "fail",
"message": "Please provide valid params",
})
}
c.Locals("bDate", date)
return c.Next()
}
func (h *BillHandler) checkIfBillExistsMiddleware(c *fiber.Ctx) error {
customContext, cancel := context.WithCancel(context.Background())
defer cancel()
targetLabelID, err := c.ParamsInt("billID")
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"status": "fail",
"message": "Please specify a valid bill ID!",
})
}
searchLabel, err := h.billService.GetBillByID(customContext, targetLabelID)
if err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
"status": "fail",
"message": err.Error(),
})
}
if searchLabel == nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
"status": "fail",
"message": "These is no bill with this ID!",
})
}
c.Locals("billID", targetLabelID)
return c.Next()
}