Skip to content

Instantly share code, notes, and snippets.

@bohdanzahurskyi1
Created December 6, 2018 19:32
Show Gist options
  • Select an option

  • Save bohdanzahurskyi1/7b1ceb68e1e49cc44fd7b3e61671ceba to your computer and use it in GitHub Desktop.

Select an option

Save bohdanzahurskyi1/7b1ceb68e1e49cc44fd7b3e61671ceba to your computer and use it in GitHub Desktop.
Gg
import { appConfig } from '@app/config'
export const paginateOptionsProvider = maxLimit => (page = 1, limit = maxLimit) => {
const newLimit = Math.min(maxLimit, limit)
const newPage = Math.max(page, 1)
const offset = Math.max((newPage - 1) * newLimit, 0)
return {
limit: newLimit,
page: newPage,
offset,
}
}
export const makePaginateOptions = paginateOptionsProvider(appConfig.maxPaginateLimit)
const getTotalPages = (count, limit) => {
const remainder = count % limit
const inc = remainder > 0 ? 1 : 0
return Math.floor(count / limit ) + inc
}
export const createQueryPaginator = queryBuilder => async (params) => {
const { limit, offset, page } = makePaginateOptions(
params.page,
params.limit
)
const { count, rows } = await queryBuilder({
limit, offset
})
const pages = getTotalPages(count, limit)
return {
data: rows,
total: count,
pages,
page,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment