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/crud.go

73 lines
1.7 KiB
Go
Raw Permalink Normal View History

2019-05-26 19:32:16 +00:00
package service
import (
"context"
"reflect"
"time"
2019-05-27 21:46:09 +00:00
"git.cliffbreak.de/haveachin/scoreboard/service/filter"
2019-05-26 19:32:16 +00:00
"go.mongodb.org/mongo-driver/bson"
)
func (s DataService) Create(v interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, err := s.collection(reflect.TypeOf(v)).InsertOne(ctx, v)
if err != nil {
return err
}
if reflect.ValueOf(v).Kind() == reflect.Ptr {
reflect.ValueOf(v).Elem().FieldByName("ID").Set(reflect.ValueOf(result.InsertedID))
}
return nil
}
2019-05-27 21:46:09 +00:00
func (s DataService) Query(v interface{}, filter *filter.Filter) error {
2019-05-26 19:32:16 +00:00
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cursor, err := s.collection(reflect.TypeOf(v)).Find(ctx, filter)
if err != nil {
return err
}
return cursor.All(ctx, v)
}
2019-05-27 21:46:09 +00:00
func (s DataService) QueryOne(v interface{}, filter *filter.Filter) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := s.collection(reflect.TypeOf(v)).FindOne(ctx, filter).Decode(v); err != nil {
return err
}
return nil
}
2019-05-26 19:32:16 +00:00
func (s DataService) Update(v interface{}, filter *filter.Filter) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := s.collection(reflect.TypeOf(v)).UpdateOne(ctx, filter, bson.M{"$set": v})
if err != nil {
return err
}
return nil
}
func (s DataService) Delete(v interface{}, filter *filter.Filter) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := s.collection(reflect.TypeOf(v)).DeleteOne(ctx, filter); err != nil {
return err
}
return nil
}