/
operations.go
97 lines (75 loc) · 2.22 KB
/
operations.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
package db
import (
"context"
"log"
"os"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
// Database name
mongoDBName = os.Getenv("MONGODB_NAME")
)
// Player document struct
type Player struct {
SteamID int64 `bson:"SteamID"`
Name string `bson:"Name"`
UpdatedAt int64 `bson:"UpdatedAt"`
}
// Chat document struct
type Chat struct {
SteamID int64 `bson:"SteamID"`
Name string `bson:"Name"`
Message string `bson:"message,omitempty"`
UpdatedAt int64 `bson:"updatedAt"`
}
// AddPlayer adds a player to the database
func AddPlayer(player Player) *mongo.UpdateResult {
// If the URI is empty, use the default
if mongoDBName == "" {
mongoDBName = "TF2"
}
// Get a handle for your collection
collection := client.Database(mongoDBName).Collection("Players")
// Filter by the steamID (64)
filter := bson.D{{Key: "SteamID", Value: player.SteamID}}
// The information to be updated
update := bson.D{{Key: "$set", Value: bson.D{
{Key: "SteamID", Value: player.SteamID},
{Key: "Name", Value: player.Name},
{Key: "UpdatedAt", Value: player.UpdatedAt},
}}}
// Upsert the document if it doesn't exist
opts := options.Update().SetUpsert(true)
// Update the document
result, err := collection.UpdateOne(context.TODO(), filter, update, opts)
if err != nil {
log.Printf("Error adding player to the DB: %v", err)
}
// fmt.Printf("Number of documents upserted: %v\n", result)
return result
}
// AddChat adds a chat message to the database
func AddChat(chat Chat) *mongo.InsertOneResult {
// If the URI is empty, use the default
if mongoDBName == "" {
mongoDBName = "TF2"
}
// Get a handle for your collection
collection := client.Database(mongoDBName).Collection("Chats")
// The information to be updated
insert := bson.D{
{Key: "SteamID", Value: chat.SteamID},
{Key: "Name", Value: chat.Name},
{Key: "Message", Value: chat.Message},
{Key: "UpdatedAt", Value: chat.UpdatedAt},
}
// Update the document
result, err := collection.InsertOne(context.TODO(), insert)
if err != nil {
log.Printf("Error adding chat to the DB: %v", err)
}
// fmt.Printf("Number of documents upserted: %v\n", result)
return result
}