-
Notifications
You must be signed in to change notification settings - Fork 0
/
access.go
64 lines (51 loc) · 1.55 KB
/
access.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
package mongodb
import (
"context"
"errors"
"reflect"
"time"
"github.com/eliezedeck/gobase/database/mongodb/codecs"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
ErrFailedCreatingDBClient = errors.New("failed creating a DB client")
ErrFailedConnecting = errors.New("failed connecting to the DB")
)
type Access struct {
dbClient *mongo.Client
dbName string
}
// NewDBAccess creates a new DBAccess, connect to the database
func NewDBAccess(uri, database string) (*Access, error) {
builder := bson.NewRegistryBuilder()
// Decoder for C# field value {"_csharpnull": true} to map to Go's *time.Time = nil
builder.RegisterTypeDecoder(reflect.TypeOf(&time.Time{}), codecs.CSharpNullTimeDecoder{})
clientOpts := options.Client().ApplyURI(uri).SetRegistry(builder.Build())
client, err := mongo.NewClient(clientOpts)
if err != nil {
return nil, ErrFailedCreatingDBClient
}
ctx, ctxCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer ctxCancel()
err = client.Connect(ctx)
if err != nil {
return nil, ErrFailedConnecting
}
access := &Access{
dbClient: client,
dbName: database,
}
return access, nil
}
func (a *Access) Collection(name string) *mongo.Collection {
return a.dbClient.Database(a.dbName).Collection(name)
}
func (a *Access) CreateIndexes(ctx context.Context, coll string, models []mongo.IndexModel) error {
c := a.Collection(coll)
if _, err := c.Indexes().CreateMany(ctx, models); err != nil {
return err
}
return nil
}