Last active
May 27, 2023 18:57
-
-
Save mostafa-hz/425b38bbd8e1770b86a04fdf6baf004c to your computer and use it in GitHub Desktop.
A function to generate keyset paginated queries for mongodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function generatePaginationQuery(query, sort, nextKey) { | |
const sortField = sort == null ? null : sort[0]; | |
function nextKeyFn(items) { | |
if (items.length === 0) { | |
return null; | |
} | |
const item = items[items.length - 1]; | |
if (sortField == null) { | |
return { _id: item._id }; | |
} | |
return { _id: item._id, [sortField]: item[sortField] }; | |
} | |
if (nextKey == null) { | |
return { paginatedQuery: query, nextKeyFn }; | |
} | |
let paginatedQuery = query; | |
if (sort == null) { | |
paginatedQuery._id = { $gt: nextKey._id }; | |
return { paginatedQuery, nextKey }; | |
} | |
const sortOperator = sort[1] === 1 ? "$gt" : "$lt"; | |
const paginationQuery = [ | |
{ [sortField]: { [sortOperator]: nextKey[sortField] } }, | |
{ | |
$and: [ | |
{ [sortField]: nextKey[sortField] }, | |
{ _id: { [sortOperator]: nextKey._id } } | |
] | |
} | |
]; | |
if (paginatedQuery.$or == null) { | |
paginatedQuery.$or = paginationQuery; | |
} else { | |
paginatedQuery = { $and: [query, { $or: paginationQuery }] }; | |
} | |
return { paginatedQuery, nextKeyFn }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@vijay122 I answered the question here: https://rawacc2031.medium.com/good-article-i-understood-how-to-fetch-next-page-one-after-other-what-if-i-want-previous-page-b642cfdcdd0f