70 lines
1.2 KiB
Go
70 lines
1.2 KiB
Go
|
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"
|
||
|
)
|