Cleaning up examples in main and splitting the code into suitable packages

This commit is contained in:
Imbus 2024-03-02 02:38:26 +01:00
parent 5cefed405f
commit 469f866554
5 changed files with 120 additions and 29 deletions

View file

@ -0,0 +1,36 @@
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
}
// "Constructor"
func NewGlobalState(db database.Database) GlobalState {
return &GState{Db: db}
}
// The global state, which implements all the handlers
type GState struct {
Db database.Database
}
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")
}

View file

@ -0,0 +1,15 @@
package handlers
import (
"testing"
"ttime/internal/database"
)
// The actual interface that we will use
func TestGlobalState(t *testing.T) {
db := database.DbConnect(":memory:")
gs := NewGlobalState(db)
if gs == nil {
t.Error("NewGlobalState returned nil")
}
}