Created
July 30, 2020 04:53
-
-
Save willikay11/3605aa969813aa8817b4d7d921bcde81 to your computer and use it in GitHub Desktop.
Paginate the data from any mode
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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};