paginate() does not work when using modify method within knex query
IvanGarzon opened this issue · comments
Hi Guys I am trying to set pagination only if the page filter is passed. Otherwise should return the regular response from the query.
If filter.page = 1
Expected:
{
data:[{...},{...},{...},{...}],
pagination:[{...},{...},{...},{...}]
}
But i am getting
[
{ user1 },
{ user2 },
{ user3 },
.
.
.
{ usern },
]
const db = require('knex');
const query = db('users');
const users = await query
.clone()
.distinct()
.select('users.*')
.orderBy('users.id', 'DESC')
.modify((query) => {
if (filters.page) {
if (!db.queryBuilder().paginate) {
attachPaginate();
}
query = query.paginate({ perPage: 20, currentPage: filters.page, isLengthAware: true });
}
});
return users;
Any help will be much appreciate it
Hi, paginate
should not be used within modify
since it returns different data structure (it may execute 2 queries behind the hood).
I would do something like:
const db = require('knex');
const { attachPaginate } = require('knex-paginate');
attachPaginate(); // this should be called only once, usually at the level of knex connection to db
function getUsers(filters) {
const baseQuery = db('users') // pay attention that there is no `await`.
.clone()
.distinct()
.select('users.*')
.orderBy('users.id', 'DESC');
const users = filters.page
? await baseQuery.paginate({ perPage: 20, currentPage: filters.page, isLengthAware: true })
: (await baseQuery).then((users) => ({ pagination: null, data: users }));
return users;
}
Pay attention that this function will return different structures, therefore I've chained the then
function.
I'll close this issue, feel free to reopen it if it wasn't solved for you.
@felixmosh Sorry for the late reply. Thanks a lot that was what I was looking for.