pagination optimization
This commit is contained in:
+12
-5
@@ -26,6 +26,8 @@ type Pagination struct {
|
||||
Cursor string `json:"cursor"` // Base64 encoded cursor for cursor-based pagination
|
||||
SortField string `json:"sortField"` // Field to sort by (default: "_id")
|
||||
SortOrder int `json:"sortOrder"` // Sort order: 1 for ascending, -1 for descending
|
||||
// Projection limits fields returned from Find (e.g. exclude large blobs on list endpoints).
|
||||
Projection bson.M `json:"projection,omitempty"`
|
||||
}
|
||||
|
||||
// PaginatedResult represents a paginated result set
|
||||
@@ -138,6 +140,10 @@ func (r *repository[T]) FindAll(ctx context.Context, filter bson.M, pagination P
|
||||
SetSort(sort).
|
||||
SetLimit(int64(pagination.Limit + 1)) // +1 to check if there are more documents
|
||||
|
||||
if len(pagination.Projection) > 0 {
|
||||
findOptions.SetProjection(pagination.Projection)
|
||||
}
|
||||
|
||||
// Handle cursor-based pagination
|
||||
if pagination.Cursor != "" {
|
||||
cursorFilter, err := r.buildCursorFilter(pagination.Cursor, pagination.SortField, pagination.SortOrder)
|
||||
@@ -181,13 +187,14 @@ func (r *repository[T]) FindAll(ctx context.Context, filter bson.M, pagination P
|
||||
items = items[:pagination.Limit] // Remove the extra item
|
||||
}
|
||||
|
||||
// Get total count
|
||||
totalCount, err := r.Count(ctx, filter)
|
||||
if err != nil {
|
||||
// Get total count for pagination metadata
|
||||
var totalCount int64
|
||||
var countErr error
|
||||
totalCount, countErr = r.Count(ctx, filter)
|
||||
if countErr != nil {
|
||||
r.logger.Error("Failed to get total count", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"error": countErr.Error(),
|
||||
})
|
||||
// Don't fail the entire query, just set count to 0
|
||||
totalCount = 0
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user