Skip to content

Instantly share code, notes, and snippets.

@willikay11
Created July 30, 2020 04:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willikay11/3605aa969813aa8817b4d7d921bcde81 to your computer and use it in GitHub Desktop.
Save willikay11/3605aa969813aa8817b4d7d921bcde81 to your computer and use it in GitHub Desktop.
Paginate the data from any mode
export const paginate = async (model, pageSize, pageLimit, search = {}, order = [], transform) => {
try {
const limit = parseInt(pageLimit, 10) || 10;
const page = parseInt(pageSize, 10) || 1;
// create an options object
let options = {
offset: getOffset(page, limit),
limit: limit,
};
// check if the search object is empty
if (Object.keys(search).length) {
options = {options, ...search};
}
// check if the order array is empty
if (order && order.length) {
options['order'] = order;
}
// take in the model, take in the options
let {count, rows} = await model.findAndCountAll(options);
// check if the transform is a function and is not null
if (transform && typeof transform === 'function') {
rows = transform(rows);
}
return {
previousPage: getPreviousPage(page),
currentPage: page,
nextPage: getNextPage(page, limit, count),
total: count,
limit: limit,
data: rows
}
} catch (error) {
console.log(error);
}
}
const getOffset = (page, limit) => {
return (page * limit) - limit;
}
const getNextPage = (page, limit, total) => {
if ((total/limit) > page) {
return page + 1;
}
return null
}
const getPreviousPage = (page) => {
if (page <= 1) {
return null
}
return page - 1;
}
@petronioamaral
Copy link

hello there,
thanks for your code, is helpful.
just on line 14 will be need a little change, destructure object options.

to: options = {...options, ...search};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment