aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/rate/rate.go
blob: df6713fd5fceb6bd988c97066fc4fdad82f4e4fb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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"
)