Created
December 6, 2018 19:32
-
-
Save bohdanzahurskyi1/7b1ceb68e1e49cc44fd7b3e61671ceba to your computer and use it in GitHub Desktop.
Gg
This file contains hidden or 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
| 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