package service import ( "context" "reflect" "time" "git.cliffbreak.de/haveachin/scoreboard/service/filter" "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 } func (s DataService) Query(v interface{}, filter *filter.Filter) error { 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) } 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 } 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 }