Skip to content

Commit

Permalink
Add pagination utils
Browse files Browse the repository at this point in the history
  • Loading branch information
protectedvoid21 committed Oct 12, 2024
1 parent fc406a8 commit f70a29e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/BHC24.Api/Extensions/QueryableExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Runtime.CompilerServices;
using BHC24.Api.Models;
using Microsoft.EntityFrameworkCore;

namespace BHC24.Api.Extensions;
Expand All @@ -13,4 +14,21 @@ public static async IAsyncEnumerable<TEntity> ToAsyncEnumerable<TEntity>(this IQ
yield return entity;
}
}

public static async Task<PaginationResponse<TEntity>> PaginateAsync<TEntity>(
this IQueryable<TEntity> query, int page, int pageSize, CancellationToken ct = default)
{
var totalItems = await query.CountAsync(ct);
var items = await query.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync(ct);

return new PaginationResponse<TEntity>
{
Data = items,
TotalCount = totalItems,
Page = page,
PageSize = pageSize
};
}
}
3 changes: 3 additions & 0 deletions src/BHC24.Api/Models/PaginationRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace BHC24.Api.Models;

public record PaginationRequest(int Page = 1, int PageSize = 20);
9 changes: 9 additions & 0 deletions src/BHC24.Api/Models/PaginationResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace BHC24.Api.Models;

public class PaginationResponse<T>
{
public int TotalCount { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
public IEnumerable<T> Data { get; set; }

Check warning on line 8 in src/BHC24.Api/Models/PaginationResponse.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'Data' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 8 in src/BHC24.Api/Models/PaginationResponse.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'Data' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
}

0 comments on commit f70a29e

Please sign in to comment.