C
C#2w ago
reeeeeee

How do you implement paging on API requests?

Basically title. Do you implement it by yourself or do you use any nuget?
7 Replies
Angius
Angius2w ago
It's super easy to just implement yourself, so using a nuget would just be a waste
public static IQueryable<T> Paginate<T>(this IQueryable<T> q, int page, int perPage)
=> q.Skip((page - 1) * perPage)
.Take(perPage);
public static IQueryable<T> Paginate<T>(this IQueryable<T> q, int page, int perPage)
=> q.Skip((page - 1) * perPage)
.Take(perPage);
's it Plug it into your EF query and you're done
Pobiega
Pobiega2w ago
I've seen a snippet/nuget around that added some PageableResponse<T> thing that added information such as total count, current page index etc so the client can make an informed request. Can't remember if it had a name thou. Its basicly what ZZZ wrote but with a few helper queries
Core
Core2w ago
Sorry, but what use does Paginate<T> have here?
Angius
Angius2w ago
var posts = await context.Blogposts
.OrderBy(p => p.ReleaseDate)
.Paginate(page, 20)
.ToListAsync();
var posts = await context.Blogposts
.OrderBy(p => p.ReleaseDate)
.Paginate(page, 20)
.ToListAsync();
Core
Core2w ago
Ohhh.... thanks
reeeeeee
reeeeeee2w ago
So all service methods shoudl be something like this, or is it any easier/better way?
public async Task<List<BlogPosts>> GetBlogposts(int? page, int? pageSize)
{
if (page.HasValue && pageSize.HasValue)
{
await context.Blogposts.OrderBy(p => p.ReleaseDate).Paginate(page, 20).ToListAsync();
}
await context.Blogposts.OrderBy(p => p.ReleaseDate).ToListAsync();
}
public async Task<List<BlogPosts>> GetBlogposts(int? page, int? pageSize)
{
if (page.HasValue && pageSize.HasValue)
{
await context.Blogposts.OrderBy(p => p.ReleaseDate).Paginate(page, 20).ToListAsync();
}
await context.Blogposts.OrderBy(p => p.ReleaseDate).ToListAsync();
}
Pobiega
Pobiega2w ago
That'll give you the items for that page. If you want to provide page count etc you'll need a wrapper
Want results from more Discord servers?
Add your server