v0.0.559 Add .Iterate and .IterateFunc methods to wmo
Some checks failed
Build Docker and Deploy / Run goext test-suite (push) Failing after 1m33s

This commit is contained in:
2025-01-28 15:55:18 +01:00
parent 06b3b4116e
commit 10a6627323
5 changed files with 105 additions and 9 deletions

View File

@@ -7,9 +7,10 @@ import (
"go.mongodb.org/mongo-driver/mongo/options"
"gogs.mikescher.com/BlackForestBytes/goext/exerr"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"iter"
)
func (c *Coll[TData]) Find(ctx context.Context, filter bson.M, opts ...*options.FindOptions) ([]TData, error) {
func (c *Coll[TData]) createFindQuery(ctx context.Context, filter bson.M, opts ...*options.FindOptions) (*mongo.Cursor, error) {
pipeline := mongo.Pipeline{}
pipeline = append(pipeline, bson.D{{Key: "$match", Value: filter}})
@@ -64,6 +65,16 @@ func (c *Coll[TData]) Find(ctx context.Context, filter bson.M, opts ...*options.
return nil, exerr.Wrap(err, "mongo-aggregation failed").Any("pipeline", pipeline).Str("collection", c.Name()).Build()
}
return cursor, nil
}
func (c *Coll[TData]) Find(ctx context.Context, filter bson.M, opts ...*options.FindOptions) ([]TData, error) {
cursor, err := c.createFindQuery(ctx, filter, opts...)
if err != nil {
return nil, exerr.Wrap(err, "").Build()
}
defer func() { _ = cursor.Close(ctx) }()
res, err := c.decodeAll(ctx, cursor)
@@ -74,6 +85,58 @@ func (c *Coll[TData]) Find(ctx context.Context, filter bson.M, opts ...*options.
return res, nil
}
func (c *Coll[TData]) IterateFunc(ctx context.Context, filter bson.M, fn func(v TData) error, opts ...*options.FindOptions) error {
cursor, err := c.createFindQuery(ctx, filter, opts...)
if err != nil {
return exerr.Wrap(err, "").Build()
}
defer func() { _ = cursor.Close(ctx) }()
for cursor.Next(ctx) {
v, err := c.decodeSingle(ctx, cursor)
if err != nil {
return exerr.Wrap(err, "").Build()
}
err = fn(v)
if err != nil {
return exerr.Wrap(err, "").Build()
}
}
return nil
}
func (c *Coll[TData]) Iterate(ctx context.Context, filter bson.M, opts ...*options.FindOptions) iter.Seq2[TData, error] {
cursor, err := c.createFindQuery(ctx, filter, opts...)
if err != nil {
return langext.IterSingleValueSeq2[TData, error](nil, exerr.Wrap(err, "").Build())
}
return func(yield func(TData, error) bool) {
defer func() { _ = cursor.Close(ctx) }()
for cursor.Next(ctx) {
v, err := c.decodeSingle(ctx, cursor)
if err != nil {
if !yield(nil, err) {
return
}
continue
}
if !yield(v, nil) {
return
}
}
}
}
// converts FindOptions to AggregateOptions
func convertFindOpt(v *options.FindOptions) (*options.AggregateOptions, error) {
if v == nil {