package handler import ( "go-rest-api/database" "go-rest-api/model" "net/http" "github.com/go-playground/validator/v10" "github.com/labstack/echo/v4" "go.mongodb.org/mongo-driver/bson" ) var ( internalErr = "Unable to operate on Article." articleNotFoundErr = "Article not found." validationErr = "Validation Error." ) // AttachArticleHandlersToRouter func func AttachArticleHandlersToRouter(e *echo.Echo) { db := database.NewMongoDb() ah := NewArticlesHandler(db) g := e.Group("/articles") g.GET("", ah.getAllArticles) g.GET("/:id", ah.getOneArticle) g.POST("", ah.createArticle) g.PUT("/:id", ah.updateArticle) g.DELETE("/:id", ah.removeArticle) } // NewArticlesHandler return ArticlesHandler func NewArticlesHandler(db *database.MongoDb) ArticlesHandler { return ArticlesHandler{ parent: BaseHandler{ db: db, validator: validator.New(), }, } } // ArticlesHandler type type ArticlesHandler struct { parent BaseHandler } func (ah *ArticlesHandler) getAllArticles(c echo.Context) error { coll := &model.Articles{} articles := ah.parent.GetAllObjects(&model.Article{}, coll, bson.D{}) return c.JSON(http.StatusOK, articles) } func (ah *ArticlesHandler) getOneArticle(c echo.Context) error { id := c.Param("id") art := &model.Article{} if _, err := ah.parent.GetSingleObject(art, id); err != nil { return err } return c.JSON(http.StatusOK, art) } func (ah *ArticlesHandler) createArticle(c echo.Context) error { art := &model.Article{} c.Bind(art) if _, err := ah.parent.CreateObject(art); err != nil { return err } return c.JSON(http.StatusOK, art) } func (ah *ArticlesHandler) updateArticle(c echo.Context) error { id := c.Param("id") model := &model.Article{} art, err := ah.parent.GetSingleObject(model, id) if err != nil { return err } DeserializeFromRequest(c.Request(), art) if _, err := ah.parent.UpdateObject(art); err != nil { return err } return c.JSON(http.StatusOK, art) } func (ah *ArticlesHandler) removeArticle(c echo.Context) error { id := c.Param("id") model := &model.Article{} art, err := ah.parent.GetSingleObject(model, id) if err != nil { return err } if err := ah.parent.RemoveObject(art); err != nil { return err } return c.NoContent(http.StatusOK) }