rest-api/handler/base.go

111 lines
2.8 KiB
Go
Raw Permalink Normal View History

package handler
import (
"encoding/json"
"go-rest-api/database"
2020-09-29 22:35:59 +02:00
"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"
)
2020-09-29 22:35:59 +02:00
var (
internalErr = "Unable to operate on Object."
objectNotFoundErr = "Object not found."
validationErr = "Validation Error."
)
// DeserializeFromRequest func
func DeserializeFromRequest(request *http.Request, output interface{}) {
2020-09-29 22:35:59 +02:00
defer request.Body.Close() // FIXME bad place for defer...?
body, _ := ioutil.ReadAll(request.Body)
_ = json.Unmarshal(body, output)
}
// BaseHandler type
type BaseHandler struct {
Queue *queue.AMQP
db *database.MongoDb
validator *validator.Validate
}
2020-09-29 22:35:59 +02:00
// NewHandler Create BaseHandler instance
func NewHandler() *BaseHandler {
return &BaseHandler{
Queue: queue.New(),
2020-09-29 22:35:59 +02:00
db: database.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 {
2020-09-29 22:35:59 +02:00
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)
}
2020-09-29 22:35:59 +02:00
// 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
}