Skip to content

Commit

Permalink
fix($Paginator): clone a query builder to prevent mutating the actual…
Browse files Browse the repository at this point in the history
… passed one

currently, the paginate function takes a query builder and mutates the query builder it takes,
This behavior can be problematic if someone intends to use the query builder again after passing it to paginate function
ex. getting the total count with or after pagination.
this commit contains fixes on both paginator class and tests
- contains a fix to the issue by just cloning the passed query builder with the class SelectQueryBuilder that clones the query builder with its query runner.
- contains a refactor to the paginator tests by not using the clone method anymore when passing the same query builder to multiple paginate function.
  • Loading branch information
mahmoudzeyada authored and benjamin658 committed Jul 12, 2022
1 parent 6b991b9 commit 4dcc6b4
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/Paginator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export default class Paginator<Entity> {
builder: SelectQueryBuilder<Entity>,
): SelectQueryBuilder<Entity> {
const cursors: CursorParam = {};
const clonedBuilder = new SelectQueryBuilder<Entity>(builder)

if (this.hasAfterCursor()) {
Object.assign(cursors, this.decode(this.afterCursor as string));
Expand All @@ -124,15 +125,15 @@ export default class Paginator<Entity> {
}

if (Object.keys(cursors).length > 0) {
builder.andWhere(
clonedBuilder.andWhere(
new Brackets((where) => this.buildCursorQuery(where, cursors)),
);
}

builder.take(this.limit + 1);
builder.orderBy(this.buildOrder());
clonedBuilder.take(this.limit + 1);
clonedBuilder.orderBy(this.buildOrder());

return builder;
return clonedBuilder;
}

private buildCursorQuery(
Expand Down

0 comments on commit 4dcc6b4

Please sign in to comment.