bill-server-go/internal/bill/handler.go

90 lines
2.2 KiB
Go
Raw Normal View History

2023-05-11 21:00:29 +08:00
package bill
import (
"context"
"github.com/gofiber/fiber/v2"
)
type BillHandler struct {
billService BillService
}
func NewBillHandler(billRoute fiber.Router, bs BillService) {
handler := &BillHandler{
billService: bs,
}
2023-06-10 16:53:19 +08:00
billRoute.Get("/:year?/:month?/:day?", handler.checkGetBillsParams, handler.getBills)
2023-05-11 21:00:29 +08:00
billRoute.Post("/", handler.createBill)
billRoute.Put("/", handler.updateBill)
billRoute.Delete("/", handler.deleteBill)
}
func (h *BillHandler) getBills(c *fiber.Ctx) error {
customContext, cancel := context.WithCancel(context.Background())
defer cancel()
2023-06-10 16:53:19 +08:00
bDate := c.Locals("bDate").(BDate)
bills, err := h.billService.GetBills(customContext, bDate)
2023-05-11 21:00:29 +08:00
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{
"status": "fail",
"message": err.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(&fiber.Map{
"status": "success",
"data": bills,
})
}
func (h *BillHandler) createBill(c *fiber.Ctx) error {
customContext, cancel := context.WithCancel(context.Background())
defer cancel()
// TODO(): create bill
err := h.billService.CreateBill(customContext, &Bill{})
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{
"status": "fail",
"message": err.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(&fiber.Map{
"status": "success",
})
}
func (h *BillHandler) updateBill(c *fiber.Ctx) error {
customContext, cancel := context.WithCancel(context.Background())
defer cancel()
// TODO(): update data
err := h.billService.UpdateBill(customContext, &Bill{})
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{
"status": "fail",
"message": err.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(&fiber.Map{
"status": "success",
})
}
func (h *BillHandler) deleteBill(c *fiber.Ctx) error {
customContext, cancel := context.WithCancel(context.Background())
defer cancel()
// TODO(): delete data id
err := h.billService.DeleteBill(customContext, 0)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{
"status": "fail",
"message": err.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(&fiber.Map{
"status": "success",
})
}