beerpong-elo/internal/repo/inMemoryRepo.go

101 lines
2.0 KiB
Go
Raw Normal View History

2025-01-05 02:57:26 +01:00
package repo
import (
"strconv"
model "git.kapelle.org/niklas/beerpong-elo/internal/model"
)
type InMemoryRepo struct {
games []model.Game
players []model.Player
2025-01-06 01:14:32 +01:00
results []model.GameResult
2025-01-05 02:57:26 +01:00
}
func NewInMemoryRepo() Repo {
return &InMemoryRepo{
games: []model.Game{},
players: []model.Player{},
2025-01-06 01:14:32 +01:00
results: []model.GameResult{},
2025-01-05 02:57:26 +01:00
}
}
2025-01-06 01:14:32 +01:00
func (r *InMemoryRepo) AddGame(game model.Game) (model.GameID, error) {
2025-01-05 02:57:26 +01:00
id := len(r.games)
parsedGame := model.Game{
2025-01-06 01:14:32 +01:00
ID: model.GameID(strconv.Itoa(id)),
2025-01-05 02:57:26 +01:00
Added: game.Added,
2025-01-06 01:14:32 +01:00
Author: game.Author,
Team0Player0: game.Team0Player0,
Team0Player1: game.Team0Player1,
Team1Player0: game.Team1Player0,
Team1Player1: game.Team1Player1,
2025-01-05 02:57:26 +01:00
Score: game.Score,
Overtime: game.Overtime,
}
r.games = append(r.games, parsedGame)
2025-01-06 01:14:32 +01:00
return model.GameID(strconv.Itoa(id)), nil
2025-01-05 02:57:26 +01:00
}
2025-01-06 01:14:32 +01:00
func (r *InMemoryRepo) GetGame(id model.GameID) (*model.Game, error) {
2025-01-05 02:57:26 +01:00
i, err := strconv.Atoi(string(id))
if err != nil {
2025-01-06 01:14:32 +01:00
return nil, err
2025-01-05 02:57:26 +01:00
}
2025-01-06 01:14:32 +01:00
return &r.games[i], nil
2025-01-05 02:57:26 +01:00
}
func (r *InMemoryRepo) GetAllGames() []model.Game {
return r.games
}
2025-01-06 01:14:32 +01:00
func (r *InMemoryRepo) GetOrCreatePlayerID(name string) (model.PlayerID, error) {
2025-01-05 02:57:26 +01:00
id := model.PlayerID(name)
for _, player := range r.players {
if player.ID == id {
2025-01-06 01:14:32 +01:00
return id, nil
2025-01-05 02:57:26 +01:00
}
}
// No player found. Create one.
r.players = append(r.players, model.NewPlayer(id))
2025-01-06 01:14:32 +01:00
return id, nil
2025-01-05 02:57:26 +01:00
}
2025-01-06 01:14:32 +01:00
func (r *InMemoryRepo) GetPlayer(id model.PlayerID) (*model.Player, error) {
2025-01-05 02:57:26 +01:00
for _, player := range r.players {
if player.ID == id {
2025-01-06 01:14:32 +01:00
return &player, nil
2025-01-05 02:57:26 +01:00
}
}
2025-01-06 01:14:32 +01:00
return nil, nil
}
func (r *InMemoryRepo) AddGameResult(result model.GameResult) (model.GameResultID, error) {
id := model.GameResultID(strconv.Itoa(len(r.results)))
result.ID = id
r.results = append(r.results, result)
return id, nil
}
2025-01-06 15:06:47 +01:00
func (r *InMemoryRepo) GetGameResult(id model.GameResultID) (*model.GameResult, error) {
2025-01-06 01:14:32 +01:00
i, err := strconv.Atoi(string(id))
if err != nil {
2025-01-06 15:06:47 +01:00
return nil, nil
2025-01-06 01:14:32 +01:00
}
2025-01-06 15:06:47 +01:00
return &r.results[i], nil
2025-01-05 02:57:26 +01:00
}