84 lines
2.2 KiB
Go
84 lines
2.2 KiB
Go
|
package handler
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"go-rest-api/database"
|
||
|
"io/ioutil"
|
||
|
"net/http"
|
||
|
|
||
|
"github.com/Kamva/mgm/v3"
|
||
|
"github.com/go-playground/validator/v10"
|
||
|
"github.com/labstack/echo/v4"
|
||
|
"go.mongodb.org/mongo-driver/bson"
|
||
|
)
|
||
|
|
||
|
// DeserializeFromRequest func
|
||
|
func DeserializeFromRequest(request *http.Request, output interface{}) {
|
||
|
defer request.Body.Close()
|
||
|
|
||
|
body, _ := ioutil.ReadAll(request.Body)
|
||
|
_ = json.Unmarshal(body, output)
|
||
|
}
|
||
|
|
||
|
// BaseHandler type
|
||
|
type BaseHandler struct {
|
||
|
db *database.MongoDb
|
||
|
validator *validator.Validate
|
||
|
}
|
||
|
|
||
|
// GetAllObjects Retrieve all objects
|
||
|
func (h *BaseHandler) GetAllObjects(model mgm.Model, coll interface{}, filter bson.D) interface{} {
|
||
|
h.db.FindAll(model, coll, filter)
|
||
|
|
||
|
return coll
|
||
|
}
|
||
|
|
||
|
// GetSingleObject Retrieve single object
|
||
|
func (h *BaseHandler) GetSingleObject(model mgm.Model, id string) (mgm.Model, *echo.HTTPError) {
|
||
|
if err := h.db.FindByID(model, id); err != nil {
|
||
|
return nil, echo.NewHTTPError(http.StatusNotFound, articleNotFoundErr)
|
||
|
}
|
||
|
|
||
|
return model, nil
|
||
|
}
|
||
|
|
||
|
// CreateObject Try to create a new object
|
||
|
func (h *BaseHandler) CreateObject(model mgm.Model) (mgm.Model, *echo.HTTPError) {
|
||
|
if err := h.Validate(model); err != nil {
|
||
|
return nil, echo.NewHTTPError(http.StatusBadRequest, validationErr+" "+err.Error())
|
||
|
}
|
||
|
|
||
|
if err := h.db.Create(model); err != nil {
|
||
|
return nil, echo.NewHTTPError(http.StatusInternalServerError, internalErr)
|
||
|
}
|
||
|
|
||
|
return model, nil
|
||
|
}
|
||
|
|
||
|
// UpdateObject Try to update a new object
|
||
|
func (h *BaseHandler) UpdateObject(model mgm.Model) (mgm.Model, *echo.HTTPError) {
|
||
|
if err := h.Validate(model); err != nil {
|
||
|
return nil, echo.NewHTTPError(http.StatusBadRequest, validationErr+" "+err.Error())
|
||
|
}
|
||
|
|
||
|
if err := h.db.Update(model); err != nil {
|
||
|
return nil, echo.NewHTTPError(http.StatusInternalServerError, internalErr)
|
||
|
}
|
||
|
|
||
|
return model, nil
|
||
|
}
|
||
|
|
||
|
//RemoveObject Try to remove object
|
||
|
func (h *BaseHandler) RemoveObject(model mgm.Model) *echo.HTTPError {
|
||
|
if err := h.db.Remove(model); err != nil {
|
||
|
return echo.NewHTTPError(http.StatusInternalServerError, internalErr)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// Validate Validate model object
|
||
|
func (h *BaseHandler) Validate(i interface{}) error {
|
||
|
return h.validator.Struct(i)
|
||
|
}
|