rest-api/handler/products.go

94 lines
2.0 KiB
Go
Raw Normal View History

2020-09-29 22:35:59 +02:00
package handler
import (
"go-rest-api/model"
"net/http"
"github.com/labstack/echo/v4"
"go.mongodb.org/mongo-driver/bson"
)
// AttachProductHandlersToRouter func
func AttachProductHandlersToRouter(e *echo.Echo) {
h := NewProductsHandler()
g := e.Group("/products")
g.GET("", h.getAllProducts)
g.GET("/:id", h.getOneProduct)
g.POST("", h.createProduct)
g.PUT("/:id", h.updateProduct)
g.DELETE("/:id", h.removeProduct)
}
// NewProductsHandler return new Products handler
func NewProductsHandler() ProductsHandler {
return ProductsHandler{BaseHandler: *NewHandler()}
}
// ProductsHandler type
type ProductsHandler struct {
BaseHandler
}
func (h *ProductsHandler) getAllProducts(c echo.Context) error {
coll := &model.Products{}
products := h.BaseHandler.GetAllObjects(&model.Product{}, coll, bson.D{})
return c.JSON(http.StatusOK, products)
}
func (h *ProductsHandler) getOneProduct(c echo.Context) error {
id := c.Param("id")
prod := &model.Product{}
if _, err := h.BaseHandler.GetSingleObject(prod, id); err != nil {
return err
}
return c.JSON(http.StatusOK, prod)
}
func (h *ProductsHandler) createProduct(c echo.Context) error {
prod := &model.Product{}
c.Bind(prod)
if _, err := h.BaseHandler.CreateObject(prod); err != nil {
return err
}
return c.JSON(http.StatusCreated, prod)
}
func (h *ProductsHandler) updateProduct(c echo.Context) error {
id := c.Param("id")
model := &model.Product{}
art, err := h.BaseHandler.GetSingleObject(model, id)
if err != nil {
return err
}
DeserializeFromRequest(c.Request(), art)
if _, err := h.BaseHandler.UpdateObject(art); err != nil {
return err
}
return c.JSON(http.StatusOK, art)
}
func (h *ProductsHandler) removeProduct(c echo.Context) error {
id := c.Param("id")
model := &model.Product{}
art, err := h.BaseHandler.GetSingleObject(model, id)
if err != nil {
return err
}
if err := h.BaseHandler.RemoveObject(art); err != nil {
return err
}
return c.NoContent(http.StatusOK)
}