logmower-shipper/pkg/mongo/mongo.go

42 lines
1.1 KiB
Go
Raw Normal View History

2022-11-09 16:07:28 +00:00
package mongo
import (
"context"
"fmt"
"net/url"
"git.k-space.ee/k-space/logmower-shipper/pkg/globals"
"go.mongodb.org/mongo-driver/mongo"
)
func Initialize(ctx context.Context, uri string) (*mongo.Collection, error) {
uriParsed, err := url.ParseRequestURI(uri)
if err != nil {
return nil, fmt.Errorf("parsing URI for database name: %w", err)
}
uriParsed.Path = uriParsed.Path[1:] // remove leading slash
if uriParsed.Path == "" {
return nil, fmt.Errorf("URI must include database name (as database to authenticate against)")
}
dbOpt := monitoredClientOptions().ApplyURI(uri)
2022-11-09 19:55:54 +00:00
dbClient, err := mongo.Connect(globals.MongoTimeout(ctx), dbOpt)
2022-11-09 16:07:28 +00:00
if err != nil {
return nil, fmt.Errorf("connecting to %q: %w", dbOpt.GetURI(), err)
}
2022-11-09 19:55:54 +00:00
if err := dbClient.Ping(globals.MongoTimeout(ctx), nil); err != nil {
return nil, fmt.Errorf("first ping to database: %w", err)
}
2022-11-09 16:07:28 +00:00
col := dbClient.Database(uriParsed.Path).Collection("logs")
if err := InitializeIndexes(globals.MongoTimeout(ctx), col); err != nil {
return nil, fmt.Errorf("initializing indexes: %w", err)
}
return col, nil
}