-
Notifications
You must be signed in to change notification settings - Fork 0
/
access.go
54 lines (43 loc) · 1.16 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
package mongodb
import (
"context"
"errors"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const DatabaseName = "bowa"
var (
ErrFailedCreatingDBClient = errors.New("failed creating a DB client")
ErrFailedConnecting = errors.New("failed connecting to the DB")
)
type Access struct {
dbClient *mongo.Client
}
// NewDBAccess creates a new DBAccess, connect to the database
func NewDBAccess(uri string) (*Access, error) {
client, err := mongo.NewClient(options.Client().ApplyURI(uri))
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,
}
return access, nil
}
func (a *Access) Collection(name string) *mongo.Collection {
return a.dbClient.Database(DatabaseName).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
}