This repository has been archived on 2019-07-11. You can view files and clone it, but cannot push or open issues or pull requests.
scoreboard/service/service.go

63 lines
1.4 KiB
Go
Raw Permalink Normal View History

2019-05-26 19:32:16 +00:00
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 nil, err
}
return &DataService{
2019-05-27 21:46:09 +00:00
client: client,
db: client.Database(ds.Database),
collections: map[reflect.Type]*mongo.Collection{},
2019-05-26 19:32:16 +00:00
}, 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) {
for t.Kind() != reflect.Struct {
t = t.Elem()
}
s.collections[t] = s.db.Collection(collection)
}