craban/server/services/store/game.go

114 lines
2 KiB
Go
Raw Normal View History

2021-09-13 14:21:37 +01:00
package store
import (
"database/sql"
sq "github.com/Masterminds/squirrel"
"git.ctrlz.es/mgdelacroix/craban/model"
)
var gameColumns = []string{"id", "user_id", "name"}
var gameMemberColumns = []string{"game_id", "user_id", "role"}
type GameStore struct {
Conn *sql.DB
}
func NewGameStore(s *Store) *GameStore {
return &GameStore{Conn: s.Conn}
}
func (gs *GameStore) Q() sq.StatementBuilderType {
return sq.StatementBuilder.RunWith(gs.Conn)
}
func (gs *GameStore) gamesFromRows(rows *sql.Rows) ([]*model.Game, error) {
games := []*model.Game{}
for rows.Next() {
var game model.Game
err := rows.Scan(
&game.ID,
&game.UserID,
&game.Name,
)
if err != nil {
return nil, err
}
games = append(games, &game)
}
return games, nil
}
func (gs *GameStore) getGameByCondition(condition sq.Eq) (*model.Game, error) {
games, err := gs.getGamesByCondition(condition)
if err != nil {
return nil, err
}
return games[0], nil
}
func (gs *GameStore) getGamesByCondition(condition sq.Eq) ([]*model.Game, error) {
rows, err := gs.Q().Select(userColumns...).
From("games").
Where(condition).
Query()
if err != nil {
return nil, err
}
defer rows.Close()
games, err := gs.gamesFromRows(rows)
if err != nil {
return nil, err
}
if len(games) == 0 {
return nil, sql.ErrNoRows
}
return games, nil
}
func (gs *GameStore) GetByID(id int) (*model.Game, error) {
return gs.getGameByCondition(sq.Eq{"id": id})
}
func (gs *GameStore) Create(name string, userID int) (*model.Game, error) {
// ToDo: generate transaction
// ToDo: add tests
res, err := gs.Q().Insert("games").
Columns(gameColumns[1:]...).
Values(name, userID).
Exec()
if err != nil {
return nil, err
}
id, err := res.LastInsertId()
if err != nil {
return nil, err
}
game, err := gs.GetByID(int(id))
if err != nil {
return nil, err
}
res, err = gs.Q().Insert("gamemember").
Columns(gameMemberColumns...).
Values(game.ID, userID, model.RoleGameMaster).
Exec()
if err != nil {
return nil, err
}
return game, nil
}