diff --git a/src/state/fsm/lobby/lobby.go b/src/state/fsm/lobby/lobby.go index 6d60f5e..aef49b7 100644 --- a/src/state/fsm/lobby/lobby.go +++ b/src/state/fsm/lobby/lobby.go @@ -3,27 +3,36 @@ package lobby import ( "context" "fmt" - "gitea/price-is-wrong/src/lib" + "gitea/price-is-wrong/src/lib/db" "io" ) type Lobby struct{} func Open(ctx context.Context, id string) (Lobby, error) { + if err := initialize(ctx); err != nil { + return Lobby{}, fmt.Errorf("failed to initialize lobbies: %w", err) + } + + if result, err := open(ctx, id); err != nil { + return Lobby{}, err + } else if result != nil { + } else if err := create(ctx, id); err != nil { + return Lobby{}, err + } + + return mustOpen(ctx, id) +} + +func mustOpen(ctx context.Context, id string) (Lobby, error) { result, err := open(ctx, id) if err != nil { return Lobby{}, err } - if result != nil { - } else if err := create(ctx, id); err != nil { - return Lobby{}, err - } else if result, err = open(ctx, id); err != nil { - return Lobby{}, err - } else if result != nil { - } else { - return Lobby{}, fmt.Errorf("unable to create new lobby %s", id) + if result == nil { + return Lobby{}, fmt.Errorf("failed to open %s", id) } - return *result, err + return *result, nil } func open(ctx context.Context, id string) (*Lobby, error) { @@ -34,8 +43,17 @@ func create(ctx context.Context, id string) error { return io.EOF } -func init(ctx context.Context) error { - _, err := lib.ExtractDB(ctx).ExecContext(ctx, ` +func initialize(ctx context.Context) error { + _, err := db.From(ctx).ExecContext(ctx, ` + CREATE TABLE IF NOT EXISTS lobbies ( + id SERIAL PRIMARY KEY + ); + CREATE TABLE IF NOT EXISTS lobbies_events ( + id SERIAL PRIMARY KEY, + lobby_id NUMBER, + payload TEXT, + FOREIGN KEY (lobby_id) REFERENCES lobbies (id) + ); `) return err } diff --git a/src/state/fsm/lobby/lobby_test.go b/src/state/fsm/lobby/lobby_test.go new file mode 100644 index 0000000..9c443aa --- /dev/null +++ b/src/state/fsm/lobby/lobby_test.go @@ -0,0 +1,15 @@ +package lobby_test + +import ( + "gitea/price-is-wrong/src/lib" + "gitea/price-is-wrong/src/state/fsm/lobby" + "testing" +) + +func TestOpen(t *testing.T) { + l, err := lobby.Open(lib.NewTestCtx(t), "id") + if err != nil { + t.Fatal(err) + } + t.Logf("%+v", l) +}