TTime/backend/internal/handlers/global_state.go

49 lines
1.1 KiB
Go
Raw Normal View History

package handlers
import (
"ttime/internal/database"
"ttime/internal/types"
"github.com/gofiber/fiber/v2"
)
// The actual interface that we will use
type GlobalState interface {
Register(c *fiber.Ctx) error
2024-03-06 09:41:36 +01:00
GetButtonCount(c *fiber.Ctx) error
IncrementButtonCount(c *fiber.Ctx) error
}
// "Constructor"
func NewGlobalState(db database.Database) GlobalState {
2024-03-06 09:41:36 +01:00
return &GState{Db: db, ButtonCount: 0}
}
// The global state, which implements all the handlers
type GState struct {
2024-03-06 09:41:36 +01:00
Db database.Database
ButtonCount int
}
func (gs *GState) Register(c *fiber.Ctx) error {
u := new(types.User)
if err := c.BodyParser(u); err != nil {
return c.Status(400).SendString(err.Error())
}
if err := gs.Db.AddUser(u.Username, u.Password); err != nil {
return c.Status(500).SendString(err.Error())
}
return c.Status(200).SendString("User added")
}
2024-03-06 09:41:36 +01:00
func (gs *GState) GetButtonCount(c *fiber.Ctx) error {
return c.Status(200).JSON(fiber.Map{"pressCount": gs.ButtonCount})
}
func (gs *GState) IncrementButtonCount(c *fiber.Ctx) error {
gs.ButtonCount++
return c.Status(200).JSON(fiber.Map{"pressCount": gs.ButtonCount})
}