v0.0.138
This commit is contained in:
75
wmo/queryList.go
Normal file
75
wmo/queryList.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package wmo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
ct "gogs.mikescher.com/BlackForestBytes/goext/cursortoken"
|
||||
)
|
||||
|
||||
func (c *Coll[TData]) List(ctx context.Context, filter ct.Filter, pageSize *int, inTok ct.CursorToken) ([]TData, ct.CursorToken, error) {
|
||||
if inTok.Mode == ct.CTMEnd {
|
||||
return make([]TData, 0), ct.End(), nil
|
||||
}
|
||||
|
||||
pipeline := filter.FilterQuery()
|
||||
|
||||
sortPrimary, sortDirPrimary, sortSecondary, sortDirSecondary := filter.Pagination()
|
||||
|
||||
paginationPipeline, err := CreatePagination(c, inTok, sortPrimary, sortDirPrimary, sortSecondary, sortDirSecondary, pageSize)
|
||||
if err != nil {
|
||||
return nil, ct.CursorToken{}, err
|
||||
}
|
||||
|
||||
pipeline = append(pipeline, paginationPipeline...)
|
||||
|
||||
cursor, err := c.coll.Aggregate(ctx, pipeline)
|
||||
if err != nil {
|
||||
return nil, ct.CursorToken{}, err
|
||||
}
|
||||
|
||||
entities := make([]TData, 0, cursor.RemainingBatchLength()+1)
|
||||
for (pageSize == nil || len(entities) != *pageSize) && cursor.Next(ctx) {
|
||||
var entry TData
|
||||
err = cursor.Decode(&entry)
|
||||
if err != nil {
|
||||
return nil, ct.CursorToken{}, err
|
||||
}
|
||||
entities = append(entities, entry)
|
||||
}
|
||||
|
||||
if pageSize == nil || len(entities) <= *pageSize || !cursor.TryNext(ctx) {
|
||||
return entities, ct.End(), nil
|
||||
}
|
||||
|
||||
last := entities[len(entities)-1]
|
||||
|
||||
nextToken, _ := c.createToken(sortPrimary, sortDirPrimary, sortSecondary, sortDirSecondary, last, pageSize)
|
||||
|
||||
return entities, nextToken, nil
|
||||
}
|
||||
|
||||
func (c *Coll[TData]) Count(ctx context.Context, filter ct.Filter) (int64, error) {
|
||||
pipeline := filter.FilterQuery()
|
||||
|
||||
pipeline = append(pipeline, bson.D{{Key: "$count", Value: "c"}})
|
||||
|
||||
cursor, err := c.coll.Aggregate(ctx, pipeline)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
type res struct {
|
||||
Count int64 `bson:"c"`
|
||||
}
|
||||
|
||||
if cursor.Next(ctx) {
|
||||
v := res{}
|
||||
err = cursor.Decode(&v)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return v.Count, nil
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
Reference in New Issue
Block a user