package handler import ( "encoding/json" "go-rest-api/database" "go-rest-api/queue" "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" ) var ( internalErr = "Unable to operate on Object." objectNotFoundErr = "Object not found." validationErr = "Validation Error." ) // DeserializeFromRequest func func DeserializeFromRequest(request *http.Request, output interface{}) { defer request.Body.Close() // FIXME bad place for defer...? body, _ := ioutil.ReadAll(request.Body) _ = json.Unmarshal(body, output) } // BaseHandler type type BaseHandler struct { db *database.MongoDb amqp *queue.AMQP validator *validator.Validate } // NewHandler Create BaseHandler instance func NewHandler() *BaseHandler { return &BaseHandler{ db: database.New(), amqp: queue.New(), validator: validator.New(), } } // 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, objectNotFoundErr) } 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) } // JsonEncode Encode *object* to string func (h *BaseHandler) JSONEncode(data interface{}) (string, error) { body, err := json.Marshal(data) if err != nil { return "", err } return string(body), nil }