v0.0.131
This commit is contained in:
parent
31418bf0e6
commit
8ac9ae0b1e
57
mongoext/aggregation.go
Normal file
57
mongoext/aggregation.go
Normal file
@ -0,0 +1,57 @@
|
||||
package mongoext
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"gogs.mikescher.com/BlackForestBytes/goext/rfctime"
|
||||
"inopart/backend/common/cursortoken"
|
||||
"inopart/backend/models"
|
||||
)
|
||||
|
||||
func HandleMongoCursorWithToken[T models.Entity](ctx context.Context, cursor *mongo.Cursor, pageSize *int) ([]T, string, error) {
|
||||
var tokenStr string
|
||||
var docs []T
|
||||
numDocs := cursor.RemainingBatchLength()
|
||||
|
||||
if pageSize == nil || (numDocs <= *pageSize) && numDocs > 0 {
|
||||
docs = make([]T, numDocs)
|
||||
|
||||
err := cursor.All(ctx, &docs)
|
||||
if err != nil {
|
||||
return []T{}, "", err
|
||||
}
|
||||
|
||||
} else if numDocs == *pageSize+1 {
|
||||
|
||||
docs = make([]T, numDocs-1)
|
||||
|
||||
for i := 0; i < numDocs-1; i++ {
|
||||
cursor.Next(ctx)
|
||||
err := cursor.Decode(&docs[i])
|
||||
if err != nil {
|
||||
return []T{}, "", err
|
||||
}
|
||||
}
|
||||
|
||||
var nextPageDoc T
|
||||
cursor.Next(ctx)
|
||||
err := cursor.Decode(&nextPageDoc)
|
||||
if err != nil {
|
||||
return []T{}, "", err
|
||||
}
|
||||
|
||||
nextPageToken := cursortoken.CursorToken{
|
||||
Timestamp: rfctime.RFC3339NanoTime{},
|
||||
Id: nextPageDoc.GetId(),
|
||||
Offset: 0,
|
||||
PageSize: *pageSize,
|
||||
}
|
||||
|
||||
tokenStr, err = nextPageToken.Token()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
|
||||
return docs, tokenStr, nil
|
||||
}
|
Loading…
Reference in New Issue
Block a user