-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver.go
80 lines (62 loc) · 1.21 KB
/
driver.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
package driver
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
type Driver struct {
client *mongo.Client
dbName string
}
type Option func(d *Driver)
func WithClient(client *mongo.Client) Option {
return func(d *Driver) {
d.client = client
}
}
func WithDbName(dbName string) Option {
return func(d *Driver) {
d.dbName = dbName
}
}
func NewWithOptions(options ...Option) (*Driver, error) {
d := &Driver{}
for _, opt := range options {
opt(d)
}
if d.client == nil {
return nil, ErrEmptyClient
}
return d, nil
}
func New(ctx context.Context) (*Driver, error) {
return NewWithConfig(ctx, DefaultConfig())
}
func NewWithConfig(ctx context.Context, config Config) (*Driver, error) {
uri, err := buildConnectionURI(&config)
if err != nil {
return nil, err
}
client, errConn := buildConnection(
ctx,
uri,
config.CertPath,
config.MinPoolSize,
config.MaxPoolSize,
)
if errConn != nil {
return nil, errConn
}
return &Driver{
client: client,
dbName: config.DBName,
}, nil
}
func (d *Driver) Client() *mongo.Client {
return d.client
}
func (d *Driver) DbName() string {
return d.dbName
}
func (d *Driver) Close() error {
return d.client.Disconnect(context.Background())
}