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")
}
}

View file

@ -0,0 +1,23 @@
package types
// User struct represents a user in the system
type User struct {
UserId string `json:"userId"`
Username string `json:"username"`
Password string `json:"password"`
}
// If the user needs to be served over the api, we dont want to send the password
// ToPublicUser converts a User to a PublicUser
func (u *User) ToPublicUser() (*PublicUser, error) {
return &PublicUser{
UserId: u.UserId,
Username: u.Username,
}, nil
}
// PublicUser represents a user that is safe to send over the API (no password)
type PublicUser struct {
UserId string `json:"userId"`
Username string `json:"username"`
}

View file

@ -0,0 +1,35 @@
package types
import "testing"
// NewUser returns a new User
func TestNewUser(t *testing.T) {
u := User{
UserId: "123",
Username: "test",
Password: "password",
}
if u.UserId != "123" {
t.Errorf("Expected user id to be 123, got %s", u.UserId)
}
if u.Username != "test" {
t.Errorf("Expected username to be test, got %s", u.Username)
}
if u.Password != "password" {
t.Errorf("Expected password to be password, got %s", u.Password)
}
}
func TestToPublicUser(t *testing.T) {
u := User{
UserId: "123",
Username: "test",
Password: "password",
}
_, err := u.ToPublicUser()
if err != nil {
t.Errorf("Expected no error, got %s", err)
}
}