paginate
The paginate method is similar to the all method, except that it will automatically apply limit and offset based on the page
and pageSize
arguments that are provided. Additionally, unlike the all
method, paginate
will return extra metadata about the requests, which is useful for driving front-end pagination tools.
await User.order('id').paginate({ pageSize: 10, page: 2 })
// {
// recordCount: 20,
// pageCount: 2,
// currentPage: 2,
// results: [User{id: 11}, User{id: 12}, ...]
// }
It is essential that you apply an order before paginating, since offset and limit both only function correctly when the order is set.
implicit pageSize
Psychic will automatically provide a default pageSize of 25, enabling you to only provide the page number when calling paginate, like so:
await User.order('id').paginate({
page: this.castParam('page', 'integer'),
})
// {
// recordCount: 25,
// pageCount: 1,
// currentPage: 1,
// results: [User{id: 1}, User{id: 2}, ..., User{id: 25}]
// }
If you would like to override the default pageSize of 25, you can do so in your conf/dream.ts
file by setting the paginationPageSize
field, like so:
// conf/dream.ts
export default (app: DreamApp) => {
app.set('paginationPageSize', 50)
}
scrollPaginate (Cursor-Based Pagination)
For high-performance scenarios with large datasets, use scrollPaginate
instead of paginate
. This method uses cursor-based pagination, which is more efficient than offset-based pagination and ideal for infinite scroll UX patterns.
await User.order('createdAt').scrollPaginate({
pageSize: 20,
cursor: 'eyJjcmVhdGVkQXQiOiIyMDI0LTAxLTE1VDEwOjAwOjAwWiJ9'
})
// {
// cursor: 'eyJjcmVhdGVkQXQiOiIyMDI0LTAxLTE1VDEwOjAwOjAwWiJ9' | null,
// results: [User{id: 1}, User{id: 2}, ...]
// }
Unlike paginate
, scrollPaginate
uses cursor-based navigation for better performance with large datasets and returns { cursor, results }
instead of page metadata. The cursor
parameter should be null
for the first page, then use the returned cursor
for subsequent pages. Like paginate
, you must apply an order before using scrollPaginate
.
Psychic provides helpful openapi controller bindings to simplify rendering paginated results from a Dream query. To learn more, see our psychic openapi pagination guides