58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
|
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
|
||
|
}
|