Skip to content

Commit

Permalink
Add pagination classes and extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
sunecko committed May 14, 2024
1 parent 9e5be7b commit 665a16d
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/TemplateFastEndpoints.API/Extensions/PaginationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using TemplateFastEndpoints.API.Utils;

namespace TemplateFastEndpoints.API.Extensions;

public static class PaginationExtensions
{
/// <summary>
/// Extension method to paginate a source collection.
/// </summary>
/// <typeparam name="T">The type of the elements in the source.</typeparam>
/// <param name="source">The source collection to paginate. Can be IQueryable or IEnumerable.</param>
/// <param name="pageNumber">The page number to retrieve.</param>
/// <param name="pageSize">The page size (number of items per page).</param>
/// <returns>A paginated response containing the items on the requested page and pagination information.</returns>
public static PaginatedResponse<T> ToPaginatedResult<T>(this IEnumerable<T> source, int pageNumber, int pageSize)
{
var enumerable = source as IQueryable<T> ?? source.AsQueryable();
var items = enumerable.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();

var totalRecords = enumerable.Count();
var totalPages = (int)Math.Ceiling((double)totalRecords / pageSize);
return new PaginatedResponse<T>(items, pageNumber, pageSize, totalPages, totalRecords);
}
}
7 changes: 7 additions & 0 deletions src/TemplateFastEndpoints.API/Utils/PaginatedRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace TemplateFastEndpoints.API.Utils;

public class PaginatedRequest
{
public int PageNumber { get; set; }
public int PageSize { get; set; }
}
19 changes: 19 additions & 0 deletions src/TemplateFastEndpoints.API/Utils/PaginatedResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace TemplateFastEndpoints.API.Utils;

public class PaginatedResponse<T>
{
public PaginatedResponse(IEnumerable<T> data, int pageNumber, int pageSize,int totalPages, int totalRecords)
{
Data = data;
PageNumber = pageNumber;
PageSize = pageSize;
TotalPages = totalPages;
TotalRecords = totalRecords;
}

public IEnumerable<T> Data { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int TotalRecords { get; set; }
}

0 comments on commit 665a16d

Please sign in to comment.