70 lines
1.5 KiB
Go
70 lines
1.5 KiB
Go
|
package service
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"reflect"
|
||
|
"time"
|
||
|
|
||
|
"github.com/haveachin/sawtexapi/service/mongodb/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, multiQuery bool) error {
|
||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||
|
defer cancel()
|
||
|
|
||
|
if !multiQuery {
|
||
|
if err := s.collection(reflect.TypeOf(v)).FindOne(ctx, filter).Decode(v); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
cursor, err := s.collection(reflect.TypeOf(v)).Find(ctx, filter)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return cursor.All(ctx, v)
|
||
|
}
|
||
|
|
||
|
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
|
||
|
}
|