summaryrefslogtreecommitdiff
path: root/pkg/api/state.go
blob: 5ddd0b38e163d492aedc13b980515fd40b49150a (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
package api

import (
	"time"

	"git.neonxp.ru/neonxp/guessr/pkg/middleware"
	"github.com/avito-tech/normalize"
	"github.com/labstack/echo/v4"
)

func (h *Handler) GetState(c echo.Context) error {
	if state := c.Get("state"); state == nil {
		return c.JSON(200, &middleware.State{})
	}

	state := c.Get("state").(*middleware.State)

	return c.JSON(200, state)
}

func (h *Handler) PostState(c echo.Context) error {
	req := &postStateRequest{}
	if err := c.Bind(req); err != nil {
		return err
	}

	username := normalize.Normalize(req.Username)
	if len(username) < 3 {
		return echo.ErrBadRequest
	}

	state := &middleware.State{
		Username: username,
	}

	if err := middleware.SetState(c, *state, int(365*24*time.Hour)); err != nil {
		return err
	}

	return c.JSON(200, state)
}

type postStateRequest struct {
	Username string `json:"username"`
}