/
chat.go
53 lines (43 loc) · 1.13 KB
/
chat.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
package mongodb
import (
"context"
"errors"
"github.com/arthurshafikov/tg-blackjack/internal/core"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Chat struct {
collection *mongo.Collection
}
func NewChat(collection *mongo.Collection) *Chat {
return &Chat{
collection: collection,
}
}
func (c *Chat) CheckChatExists(ctx context.Context, telegramChatID int64) error {
filter := bson.M{core.TelegramChatIDField: telegramChatID}
if err := c.collection.FindOne(ctx, filter).Err(); err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return core.ErrNotFound
}
return err
}
return nil
}
func (c *Chat) RegisterChat(ctx context.Context, telegramChatID int64) error {
filter := bson.M{
core.TelegramChatIDField: telegramChatID,
}
chat := core.Chat{
TelegramChatID: telegramChatID,
Statistics: core.UsersStatistics{},
Deck: core.NewDeckWithCards(core.Cards{}),
}
update := bson.M{
"$setOnInsert": chat,
}
opts := options.Update().SetUpsert(true)
_, err := c.collection.UpdateOne(ctx, filter, update, opts)
return err
}