/
leaf.go
50 lines (40 loc) · 1.07 KB
/
leaf.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
package mongoleaf
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Branch struct {
Client *mongo.Client
}
type dataBase struct {
DB *mongo.Database
}
type colletion struct {
Colletion *mongo.Collection
}
func New(URI string) (Branch, error) {
c, err := connect(URI)
if err != nil {
return Branch{}, err
}
return Branch{Client: c}, nil
}
func connect(URI string) (*mongo.Client, error) {
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(URI))
if err != nil {
return nil, err
}
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
// log.Printf("mongodb Faild to send Ping to MongoDB with '%v' URI. \t Error Value: %v. \n", URI, err)
return nil, err
}
return client, nil
}
func (branch Branch) DataBase(dataBaseName string) dataBase {
return dataBase{DB: branch.Client.Database(dataBaseName)}
}
func (db dataBase) Colletion(colletionName string) colletion {
return colletion{Colletion: db.DB.Collection(colletionName)}
}