-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
72 lines (62 loc) · 1.49 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package sweeper
import (
"context"
"fmt"
"github.com/google/uuid"
)
type GameMutator func(ctx context.Context, g *Game) error
type Store interface {
SaveGame(ctx context.Context, game *Game) error
GetGame(ctx context.Context, gameID uuid.UUID) (*Game, error)
MutateGame(
ctx context.Context,
gameID uuid.UUID,
mut GameMutator,
) (*Game, error)
}
type Service struct {
store Store
idGen IDGenerator
numberGen NumberGenerator
}
func NewService(store Store, idGen IDGenerator, numberGen NumberGenerator) Service {
return Service{
store: store,
idGen: idGen,
numberGen: numberGen,
}
}
func (s Service) StartGame(ctx context.Context, board Board) (*Game, error) {
g, err := NewGame(ctx, s.idGen, s.numberGen, board)
if err != nil {
return nil, fmt.Errorf("creating game: %w", err)
}
if err := s.store.SaveGame(ctx, g); err != nil {
return nil, fmt.Errorf("saving game: %w", err)
}
return g, nil
}
func (s Service) GetGame(ctx context.Context, gameID uuid.UUID) (*Game, error) {
return s.store.GetGame(ctx, gameID)
}
func (s Service) EndGame(ctx context.Context, gameID uuid.UUID) (*Game, error) {
return s.store.MutateGame(
ctx,
gameID,
func(ctx context.Context, g *Game) error { return g.End() },
)
}
func (s Service) MakeMove(
ctx context.Context,
gameID uuid.UUID,
ref CellRef,
toState CellState,
) (*Game, error) {
return s.store.MutateGame(
ctx,
gameID,
func(ctx context.Context, g *Game) error {
return g.UpdateCell(ref, toState)
},
)
}