34 lines
738 B
Go
34 lines
738 B
Go
|
|
// Package database define database operation functions
|
||
|
|
package database
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"sync"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"eventRT/config"
|
||
|
|
|
||
|
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
|
)
|
||
|
|
|
||
|
|
var (
|
||
|
|
_globalMongoClient *mongo.Client
|
||
|
|
mongoOnce sync.Once
|
||
|
|
)
|
||
|
|
|
||
|
|
// InitMongoInstance return instance of MongoDB client
|
||
|
|
func InitMongoInstance(ctx context.Context, mCfg config.MongoDBConfig) *mongo.Client {
|
||
|
|
mongoOnce.Do(func() {
|
||
|
|
cancelCtx, cancel := context.WithTimeout(ctx, time.Duration(mCfg.Timeout)*time.Second)
|
||
|
|
defer cancel()
|
||
|
|
|
||
|
|
client, err := mongo.Connect(cancelCtx, options.Client().ApplyURI(mCfg.URI))
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
_globalMongoClient = client
|
||
|
|
})
|
||
|
|
return _globalMongoClient
|
||
|
|
}
|