diff --git a/src/makePaginate.ts b/src/makePaginate.ts index 14d9ee4..44457a6 100644 --- a/src/makePaginate.ts +++ b/src/makePaginate.ts @@ -8,6 +8,7 @@ import { reverseOrder, getPrimaryKeyFields, isModelClass, + getCount, } from './utils'; import { @@ -81,8 +82,8 @@ const makePaginate = ( const [instances, totalCount, cursorCount] = await Promise.all([ modelClass.findAll(paginationQueryOptions), - modelClass.count(totalCountQueryOptions), - modelClass.count(cursorCountQueryOptions), + getCount(modelClass, totalCountQueryOptions), + getCount(modelClass, cursorCountQueryOptions), ]); if (before) { diff --git a/src/tests/makePaginate.test.ts b/src/tests/makePaginate.test.ts index 3b785ba..474d1ba 100644 --- a/src/tests/makePaginate.test.ts +++ b/src/tests/makePaginate.test.ts @@ -207,4 +207,13 @@ describe('makePaginate', () => { expectIdsToEqual(result, [5, 4, 3]); expect(result.totalCount).toBe(3); }); + + it('paginates correctly with group by', async () => { + await generateTestData(); + + const result = await Counter.paginate({ group: 'extra' }); + + expectIdsToEqual(result, [1, 3]); + expect(result.totalCount).toBe(2); + }); }); diff --git a/src/utils.ts b/src/utils.ts index 6559e52..c275336 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,4 @@ -import { Op, ModelStatic, WhereOptions, Model } from 'sequelize'; +import { Op, ModelStatic, WhereOptions, Model, CountOptions } from 'sequelize'; import { CursorPayload, OrderConfig } from './types'; export const parseCursor = (cursor: string): CursorPayload | null => { @@ -141,3 +141,17 @@ export const getPaginationQuery = ( export const isModelClass = (value: unknown): value is ModelStatic => { return typeof value === 'function' && value.prototype instanceof Model; }; + +export const getCount = async ( + model: ModelStatic, + query: CountOptions, +): Promise => { + const countPayload = await model.count(query); + + // count with group by query returns an array + if (Array.isArray(countPayload)) { + return countPayload.length; + } + + return countPayload; +};