-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
71 lines (55 loc) · 1.57 KB
/
database.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
package gomongo
import (
"context"
"errors"
"fmt"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
ErrGomongoCanNotConnect = errors.New("gomongo can not connect to mongodb")
)
type Database struct {
mongoDatabase *mongo.Database
}
func NewDatabase(ctx context.Context, cs ConnectionSettings) (Database, error) {
if err := cs.validate(); err != nil {
return Database{}, err
}
mongoClient, err := mongoClient(ctx, &cs)
if err != nil {
return Database{}, fmt.Errorf("%w: %w", ErrGomongoCanNotConnect, err)
}
if err := pingMongoServer(&cs, mongoClient, ctx); err != nil {
return Database{}, fmt.Errorf("%w: %w", ErrGomongoCanNotConnect, err)
}
return Database{
mongoClient.Database(cs.DatabaseName),
}, nil
}
func mongoClient(ctx context.Context, cs *ConnectionSettings) (*mongo.Client, error) {
return mongo.Connect(ctx, clientOptions(cs))
}
func clientOptions(cs *ConnectionSettings) *options.ClientOptions {
clientOptions := options.Client().ApplyURI(cs.URI)
if cs.ConnectionTimeout > 0 {
clientOptions.SetConnectTimeout(cs.ConnectionTimeout)
}
return clientOptions
}
func pingMongoServer(cs *ConnectionSettings, mongoClient *mongo.Client, ctx context.Context) error {
pingTimeout := cs.ConnectionTimeout
if pingTimeout <= 0 {
pingTimeout = 30 * time.Second
}
ctx, cancelFunc := context.WithTimeout(ctx, pingTimeout)
defer cancelFunc()
return mongoClient.Ping(ctx, nil)
}
func validateDatabase(database Database) error {
if database.mongoDatabase == nil {
return ErrConnectionNotInitialized
}
return nil
}