Extract links manipulation endpoints in separate resource

This commit is contained in:
Andrey Chervyakov 2021-03-13 17:18:23 +06:00
parent 2eea43d973
commit 750899c93f

View file

@ -7,6 +7,23 @@ import (
"net/http" "net/http"
) )
func redirectHandler(c echo.Context, pool *pgxpool.Pool) error {
linkId := c.Param("id")
rep := PgRepository{pool: pool}
link, err := rep.FindById(linkId)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError)
}
if link == nil {
return echo.NewHTTPError(http.StatusNotFound, "Link with given ID was not found.")
}
return c.Redirect(http.StatusSeeOther, link.RedirectURL.String())
}
func creationHandler(c echo.Context, pool *pgxpool.Pool) error { func creationHandler(c echo.Context, pool *pgxpool.Pool) error {
var model CreationModel var model CreationModel
if err := json.NewDecoder(c.Request().Body).Decode(&model); err != nil { if err := json.NewDecoder(c.Request().Body).Decode(&model); err != nil {
@ -36,23 +53,6 @@ func creationHandler(c echo.Context, pool *pgxpool.Pool) error {
return c.NoContent(http.StatusCreated) return c.NoContent(http.StatusCreated)
} }
func redirectHandler(c echo.Context, pool *pgxpool.Pool) error {
linkId := c.Param("id")
rep := PgRepository{pool: pool}
link, err := rep.FindById(linkId)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError)
}
if link == nil {
return echo.NewHTTPError(http.StatusNotFound, "Link with given ID was not found.")
}
return c.Redirect(http.StatusSeeOther, link.RedirectURL.String())
}
func removalHandler(c echo.Context, pool *pgxpool.Pool) error { func removalHandler(c echo.Context, pool *pgxpool.Pool) error {
linkId := c.Param("id") linkId := c.Param("id")
@ -66,15 +66,17 @@ func removalHandler(c echo.Context, pool *pgxpool.Pool) error {
} }
func AddHandlers(s *echo.Echo, pool *pgxpool.Pool) { func AddHandlers(s *echo.Echo, pool *pgxpool.Pool) {
s.POST("", func(ctx echo.Context) error { gr := s.Group("/links")
gr.POST("", func(ctx echo.Context) error {
return creationHandler(ctx, pool) return creationHandler(ctx, pool)
}) })
gr.DELETE("/:id", func(ctx echo.Context) error {
return removalHandler(ctx, pool)
})
s.GET("/:id", func(ctx echo.Context) error { s.GET("/:id", func(ctx echo.Context) error {
return redirectHandler(ctx, pool) return redirectHandler(ctx, pool)
}) })
s.DELETE("/:id", func(ctx echo.Context) error {
return removalHandler(ctx, pool)
})
} }