/
provider.go
43 lines (33 loc) · 934 Bytes
/
provider.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
package mongodb
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// NewConfigWith returns a new configuration with specific parameters
func NewConfigWith(connectionUrl string, dbName string, collection string) Config {
return Config{
ConnectionUrl: connectionUrl,
Database: dbName,
Collection: collection,
}
}
// New returns a new configured mongodb provider
func New(cfg Config) (*Provider, error) {
serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1)
clientOptions := options.Client().
ApplyURI(cfg.ConnectionUrl).
SetServerAPIOptions(serverAPIOptions)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
return nil, newErrMongoConnection(err)
}
p := &Provider{
config: cfg,
db: client,
}
return p, nil
}