-
Notifications
You must be signed in to change notification settings - Fork 2
/
connector.go
69 lines (56 loc) · 1.46 KB
/
connector.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
package gomongowrapper
import (
"strings"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/tag"
)
// NewConnector returns a new database connector for the application.
func NewConnector(config Config) (*Client, error) {
opts := options.Client()
if config.URI != "" {
opts = opts.ApplyURI(config.URI)
}
if len(config.Hosts) > 0 {
opts = opts.SetHosts(config.Hosts)
}
if config.User != "" {
opts = opts.SetAuth(options.Credential{
AuthSource: config.Name,
Username: config.User,
Password: config.Pass,
})
}
if config.ReplicaSet != nil {
opts.ReplicaSet = config.ReplicaSet
}
if config.ReadPreference != nil {
var rpOpts []readpref.Option
if config.ReadPreference.MaxStaleness != nil {
rpOpts = append(rpOpts, readpref.WithMaxStaleness(*config.ReadPreference.MaxStaleness))
}
if len(config.ReadPreference.Tags) > 0 {
var tagSet tag.Set
for _, t := range config.ReadPreference.Tags {
if t == "" {
tagSet = append(tagSet, tag.Tag{})
break
}
kv := strings.Split(t, ":")
if len(kv) != 2 {
continue
}
tagSet = append(tagSet, tag.Tag{Name: kv[0], Value: kv[1]})
}
if len(tagSet) > 0 {
rpOpts = append(rpOpts, readpref.WithTagSets(tagSet))
}
}
var err error
opts.ReadPreference, err = readpref.New(config.ReadPreference.Mode, rpOpts...)
if err != nil {
return nil, err
}
}
return NewClient(opts)
}