package service
import (
"context"
"fmt"
"net/url"
"reflect"
"time"
"git.cliffbreak.de/haveachin/scoreboard/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type DataService struct {
client *mongo.Client
db *mongo.Database
collections map[reflect.Type]*mongo.Collection
}
func New(ds config.DataService) (*DataService, error) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
connectionString := fmt.Sprintf("mongodb://%s:%s@%s:%d/?authSource=admin", url.QueryEscape(ds.Username), url.QueryEscape(ds.Password), ds.IP, ds.Port)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(connectionString))
if err != nil {
return nil, err
if err = client.Ping(ctx, readpref.Primary()); err != nil {
return &DataService{
client: client,
db: client.Database(ds.Database),
collections: map[reflect.Type]*mongo.Collection{},
}, nil
func (s DataService) collection(t reflect.Type) *mongo.Collection {
for t.Kind() != reflect.Struct {
t = t.Elem()
collection, ok := s.collections[t]
if !ok {
panic(fmt.Sprintf("No collection registered for %T", t))
return collection
func (s DataService) RegisterCollection(t reflect.Type, collection string) {
s.collections[t] = s.db.Collection(collection)