diff --git a/src/TemplateFastEndpoints.API/Extensions/PaginationExtensions.cs b/src/TemplateFastEndpoints.API/Extensions/PaginationExtensions.cs new file mode 100644 index 0000000..9063b90 --- /dev/null +++ b/src/TemplateFastEndpoints.API/Extensions/PaginationExtensions.cs @@ -0,0 +1,24 @@ +using TemplateFastEndpoints.API.Utils; + +namespace TemplateFastEndpoints.API.Extensions; + +public static class PaginationExtensions +{ + /// + /// Extension method to paginate a source collection. + /// + /// The type of the elements in the source. + /// The source collection to paginate. Can be IQueryable or IEnumerable. + /// The page number to retrieve. + /// The page size (number of items per page). + /// A paginated response containing the items on the requested page and pagination information. + public static PaginatedResponse ToPaginatedResult(this IEnumerable source, int pageNumber, int pageSize) where T : class + { + var enumerable = source as IQueryable ?? 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(items, pageNumber, pageSize, totalPages, totalRecords); + } +} \ No newline at end of file diff --git a/src/TemplateFastEndpoints.API/Utils/PaginatedRequest.cs b/src/TemplateFastEndpoints.API/Utils/PaginatedRequest.cs new file mode 100644 index 0000000..df0e08d --- /dev/null +++ b/src/TemplateFastEndpoints.API/Utils/PaginatedRequest.cs @@ -0,0 +1,7 @@ +namespace TemplateFastEndpoints.API.Utils; + +public class PaginatedRequest +{ + public int PageNumber { get; set; } + public int PageSize { get; set; } +} \ No newline at end of file diff --git a/src/TemplateFastEndpoints.API/Utils/PaginatedResponse.cs b/src/TemplateFastEndpoints.API/Utils/PaginatedResponse.cs new file mode 100644 index 0000000..ca507bc --- /dev/null +++ b/src/TemplateFastEndpoints.API/Utils/PaginatedResponse.cs @@ -0,0 +1,19 @@ +namespace TemplateFastEndpoints.API.Utils; + +public class PaginatedResponse where T : class +{ + public PaginatedResponse(IEnumerable data, int pageNumber, int pageSize,int totalPages, int totalRecords) + { + Data = data; + PageNumber = pageNumber; + PageSize = pageSize; + TotalPages = totalPages; + TotalRecords = totalRecords; + } + + public IEnumerable Data { get; set; } + public int PageNumber { get; set; } + public int PageSize { get; set; } + public int TotalPages { get; set; } + public int TotalRecords { get; set; } +} \ No newline at end of file