You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mongox-go-driver/mongox/common/loadarray.go

72 lines
1.7 KiB

6 years ago
package common
import (
"reflect"
"github.com/mainnika/mongox-go-driver/mongox"
"github.com/mainnika/mongox-go-driver/mongox/errors"
"github.com/mainnika/mongox-go-driver/mongox/query"
"go.mongodb.org/mongo-driver/mongo"
6 years ago
)
// LoadArray loads an array of documents from the database by query
func LoadArray(db *mongox.Database, target interface{}, filters ...interface{}) error {
6 years ago
targetV := reflect.ValueOf(target)
targetT := targetV.Type()
targetK := targetV.Kind()
if targetK != reflect.Ptr {
panic(errors.InternalErrorf("target is not a ptr"))
}
targetSliceV := targetV.Elem()
targetSliceT := targetT.Elem()
if targetSliceT.Kind() != reflect.Slice {
panic(errors.InternalErrorf("target should be a ptr to a slice"))
}
targetSliceElemT := targetSliceT.Elem()
if targetSliceElemT.Kind() != reflect.Ptr {
panic(errors.InternalErrorf("target slice should contain ptrs"))
}
composed := query.Compose(filters...)
hasPreloader, _ := composed.Preloader()
6 years ago
var result *mongo.Cursor
var err error
6 years ago
if hasPreloader {
result, err = createAggregateLoad(db, target, composed)
} else {
result, err = createSimpleLoad(db, target, composed)
}
6 years ago
if err != nil {
return errors.InternalErrorf("can't create find result: %s", err)
}
defer result.Close(db.Context())
var i int
for i = 0; result.Next(db.Context()); {
6 years ago
if targetSliceV.Len() == i {
elem := reflect.New(targetSliceElemT.Elem())
if err = result.Decode(elem.Interface()); err == nil {
targetSliceV = reflect.Append(targetSliceV, elem)
} else {
continue
6 years ago
}
} else if err = result.Decode(targetSliceV.Index(i).Interface()); err != nil {
continue
6 years ago
}
i++
6 years ago
}
targetSliceV = targetSliceV.Slice(0, i)
targetV.Elem().Set(targetSliceV)
return nil
}