/
space.go
100 lines (88 loc) · 1.98 KB
/
space.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package mongodbspace
import (
"context"
"time"
"github.com/theothertomelliott/tic-tac-toverengineered/common/player"
"github.com/theothertomelliott/tic-tac-toverengineered/services/gamerepo/pkg/game"
space "github.com/theothertomelliott/tic-tac-toverengineered/services/space/pkg"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var _ space.Space = &Space{}
// New creates a Space backed by MongoDB.
func New(
ctx context.Context,
collection *mongo.Collection,
x, y int,
) (space.Space, error) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
// Add unique index on Game and Position
_, err := collection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{
{Key: "game", Value: 1},
{Key: "position", Value: 1},
},
Options: options.Index().SetUnique(true),
})
if err != nil {
return nil, err
}
return &Space{
collection: collection,
pos: position{
X: x,
Y: y,
},
}, nil
}
type Space struct {
collection *mongo.Collection
pos position
}
func (s *Space) Mark(ctx context.Context, gameID game.ID) (*player.Mark, error) {
var result struct {
ID string `bson:"_id"`
Mark *player.Mark
}
var filter = struct {
Position position
Game game.ID
}{
Position: s.pos,
Game: gameID,
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
res := s.collection.FindOne(ctx, filter)
if res.Err() == mongo.ErrNoDocuments {
return nil, nil
}
err := res.Decode(&result)
return result.Mark, err
}
func (s *Space) SetMark(ctx context.Context, gameID game.ID, m player.Mark) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_, err := s.collection.UpdateOne(ctx,
bson.M{
"position": s.pos,
"game": gameID,
},
bson.M{
"$set": bson.M{
"mark": &m,
},
},
options.Update().SetUpsert(true),
)
if err != nil {
return err
}
return nil
}
type position struct {
X int
Y int
}