diff options
Diffstat (limited to 'pkg/handler/rate/rate.go')
-rw-r--r-- | pkg/handler/rate/rate.go | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/pkg/handler/rate/rate.go b/pkg/handler/rate/rate.go new file mode 100644 index 0000000..df6713f --- /dev/null +++ b/pkg/handler/rate/rate.go @@ -0,0 +1,69 @@ +package rate + +import ( + "strconv" + + "github.com/labstack/echo-contrib/session" + "github.com/labstack/echo/v4" + "sh.org.ru/pkg/model" + "sh.org.ru/pkg/tpl" +) + +func (h *Handler) Rate(c echo.Context) error { + voted, err := session.Get("votes", c) + if err != nil { + return err + } + sid := c.Param("id") + id, err := strconv.Atoi(sid) + if err != nil { + return err + } + f := new(rateForm) + if err := c.Bind(f); err != nil { + return err + } + + quote := new(model.Quote) + + if _, ok := voted.Values[id]; !ok { + voted.Values[id] = true + if err := voted.Save(c.Request(), c.Response()); err != nil { + return err + } + set := "" + switch f.Vote { + case "up": + set = "rating = rating + 1" + case "down": + set = "rating = rating - 1" + } + _, err = h.db.NewUpdate(). + Model(quote). + Where("id = ?", id). + Set(set). + Returning("*"). + Exec(c.Request().Context(), quote) + } else { + err = h.db.NewSelect(). + Model(quote). + Where("id = ?", id). + Scan(c.Request().Context(), quote) + } + if err != nil { + return err + } + + return tpl.Rate(quote, 0).Render(c.Request().Context(), c.Response()) +} + +type rateForm struct { + Vote string `form:"vote"` +} + +type voteType string + +const ( + voteUp voteType = "up" + voteDown voteType = "down" +) |