aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/rate/rate.go
diff options
context:
space:
mode:
authorAlexander Neonxp Kiryukhin <i@neonxp.ru>2024-10-08 03:43:08 +0300
committerAlexander Neonxp Kiryukhin <i@neonxp.ru>2024-10-08 03:50:53 +0300
commite849e705c30cceec3cf7336a21bed96c8a911e90 (patch)
tree93f559bcd4cf3e53193930d112e564a2b7462ac8 /pkg/handler/rate/rate.go
parent3ee654f6fb3cdf119630bfba8066c96ec26428c3 (diff)
Добавил рейтинг
Добавил страницу топа Добавил rss/xml/json feed
Diffstat (limited to 'pkg/handler/rate/rate.go')
-rw-r--r--pkg/handler/rate/rate.go69
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"
+)