Skip to content

Commit

Permalink
support group by queries
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaltsoon committed Nov 2, 2022
1 parent 5f6c744 commit f9c850f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/makePaginate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
reverseOrder,
getPrimaryKeyFields,
isModelClass,
getCount,
} from './utils';

import {
Expand Down Expand Up @@ -81,8 +82,8 @@ const makePaginate = <ModelType extends Model>(

const [instances, totalCount, cursorCount] = await Promise.all([
modelClass.findAll(paginationQueryOptions),
modelClass.count(totalCountQueryOptions),
modelClass.count(cursorCountQueryOptions),
getCount(modelClass, totalCountQueryOptions),
getCount(modelClass, cursorCountQueryOptions),
]);

if (before) {
Expand Down
9 changes: 9 additions & 0 deletions src/tests/makePaginate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
16 changes: 15 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -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 => {
Expand Down Expand Up @@ -141,3 +141,17 @@ export const getPaginationQuery = (
export const isModelClass = (value: unknown): value is ModelStatic<any> => {
return typeof value === 'function' && value.prototype instanceof Model;
};

export const getCount = async (
model: ModelStatic<any>,
query: CountOptions<any>,
): Promise<number> => {
const countPayload = await model.count(query);

// count with group by query returns an array
if (Array.isArray(countPayload)) {
return countPayload.length;
}

return countPayload;
};

0 comments on commit f9c850f

Please sign in to comment.