forked from Southclaws/cj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot_db.go
73 lines (62 loc) · 1.79 KB
/
bot_db.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
package main
import (
"fmt"
"go.uber.org/zap"
"gopkg.in/mgo.v2"
)
// ConnectDB connects and authenticates against a MongoDB server
func (app *App) ConnectDB() {
var err error
app.mongo, err = mgo.Dial(fmt.Sprintf("%s:%s", app.config.MongoHost, app.config.MongoPort))
if err != nil {
logger.Fatal("failed to connect to mongodb",
zap.String("host", app.config.MongoHost),
zap.String("port", app.config.MongoPort),
zap.Error(err))
}
logger.Info("connected to mongodb server")
if app.config.MongoPass != "" {
err = app.mongo.Login(&mgo.Credential{
Source: app.config.MongoName,
Username: app.config.MongoUser,
Password: app.config.MongoPass,
})
if err != nil {
logger.Fatal("failed to log in to mongodb",
zap.Error(err))
}
logger.Info("logged in to mongodb server")
}
if !app.CollectionExists("accounts") {
err = app.mongo.DB(app.config.MongoName).C("accounts").Create(&mgo.CollectionInfo{})
if err != nil {
logger.Fatal("collection create failed",
zap.String("collection", "accounts"),
zap.Error(err))
}
}
if !app.CollectionExists("chat") {
err = app.mongo.DB(app.config.MongoName).C("chat").Create(&mgo.CollectionInfo{})
if err != nil {
logger.Fatal("collection create failed",
zap.String("collection", "chat"),
zap.Error(err))
}
}
app.accounts = app.mongo.DB(app.config.MongoName).C("accounts")
app.chat = app.mongo.DB(app.config.MongoName).C("chat")
}
// CollectionExists checks if a collection exists in MongoDB
func (app *App) CollectionExists(name string) bool {
collections, err := app.mongo.DB(app.config.MongoName).CollectionNames()
if err != nil {
logger.Fatal("failed to get collection names",
zap.Error(err))
}
for _, collection := range collections {
if collection == name {
return true
}
}
return false
}