-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdb.go
More file actions
81 lines (63 loc) · 1.78 KB
/
db.go
File metadata and controls
81 lines (63 loc) · 1.78 KB
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
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
"os"
"time"
)
var Client = Connect()
var db = os.Getenv("MONGO_DB")
var dbUri = os.Getenv("MONGO_URI")
func Connect() *mongo.Client {
ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
defer cancel()
opts := options.Client().ApplyURI(dbUri)
client, err := mongo.Connect(ctx, opts)
if err != nil {
log.Panicln(`error connecting to database`, err)
}
if err = client.Ping(ctx, readpref.Primary()); err != nil {
log.Panicln("error pinging database", err)
}
log.Println("connected to mongodb")
return client
}
type Relation struct {
EboardTS string `bson:eboardTS`
ClientID string `bson:clientID`
ClientTS string `bson:clientTS`
}
func LoadRelations() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cursor, err := Client.Database(db).Collection("relations").Find(ctx, bson.D{})
if err != nil {
fmt.Println("HELP", err)
return
}
relations := make([]Relation, 0)
err = cursor.All(ctx, &relations)
if err != nil {
fmt.Println("HELP", err)
return
}
for _, relation := range relations {
clientString := relation.ClientID + ":" + relation.ClientTS
EboardRelations[relation.EboardTS] = clientString
ClientRelations[clientString] = relation.EboardTS
}
}
func MakeRelation(eboardTS, clientID, clientTS string) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
newRelation := Relation{EboardTS: eboardTS, ClientTS: clientTS, ClientID: clientID}
_, err := Client.Database(db).Collection("relations").InsertOne(ctx, newRelation)
if err != nil {
return
}
}