Skip to content

Commit bff7022

Browse files
committed
Refactored code based and extended with PageSize, PageNumber and TotalPages
1 parent 38cc386 commit bff7022

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

NorthwindCRUD/Controllers/ProductsController.cs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,26 +52,35 @@ public ActionResult<ProductDto[]> GetAll()
5252
[HttpGet("GetAllPagedProducts")]
5353
public ActionResult<ProductDtoCollection> GetAllProducts(int? skip, int? top)
5454
{
55-
int skipRecordsAmount = skip ?? 0;
56-
int currentSize = top ?? 0;
57-
5855
try
5956
{
57+
// Retrieve all products
6058
var products = this.productService.GetAll();
6159
var totalRecords = products.Length;
6260

61+
// Default skip and top if not provided
62+
int skipRecordsAmount = skip ?? 0;
63+
int currentSize = top ?? totalRecords;
64+
65+
// Apply pagination
6366
var pagedProducts = products
6467
.Skip(skipRecordsAmount)
6568
.Take(currentSize)
6669
.ToArray();
6770

68-
// Create a new ProductDtoCollection object
69-
// TODO, return also Page size, Page and totalPages = (int)Math.Ceiling(totalRecords / (double)currentSize);
71+
// Calculate total pages
72+
int totalPages = (int)Math.Ceiling(totalRecords / (double)currentSize);
73+
74+
// Create and return the product collection
7075
var productCollection = new ProductDtoCollection
7176
{
7277
// Check if both pageNumber and pageSize are null, if so, return all products
73-
Products = this.mapper.Map<ProductDb[], ProductDto[]>((skipRecordsAmount == 0 && currentSize == 0) ? products : pagedProducts),
78+
Products = this.mapper.Map<ProductDb[], ProductDto[]>(pagedProducts),
7479
TotalRecordsCount = totalRecords,
80+
PageSize = currentSize,
81+
PageNumber = (skipRecordsAmount / currentSize) + 1,
82+
TotalPages = totalPages,
83+
7584
};
7685

7786
return Ok(productCollection);

NorthwindCRUD/Models/Dtos/ProductDtoCollection.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,11 @@ public class ProductDtoCollection
88
public ICollection<ProductDto> Products { get; set; } = new List<ProductDto>();
99

1010
public int TotalRecordsCount { get; set; }
11+
12+
public int PageSize { get; set; }
13+
14+
public int PageNumber { get; set; }
15+
16+
public int TotalPages { get; set; }
1117
}
1218
}

0 commit comments

Comments
 (0)