C
C#2mo 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
Angius2mo 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
Pobiega2mo 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
Core2mo ago
Sorry, but what use does Paginate<T> have here?
Angius
Angius2mo 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
Core2mo ago
Ohhh.... thanks
reeeeeee
reeeeeeeOP2mo 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
Pobiega2mo 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