From 4dcc6b450be885d42f7990f66346aba9de70a4fc Mon Sep 17 00:00:00 2001 From: mahmoudzeyada Date: Mon, 11 Jul 2022 13:26:12 +0200 Subject: [PATCH] fix($Paginator): clone a query builder to prevent mutating the actual 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. --- src/Paginator.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Paginator.ts b/src/Paginator.ts index cd0a00f..d6d7849 100644 --- a/src/Paginator.ts +++ b/src/Paginator.ts @@ -116,6 +116,7 @@ export default class Paginator { builder: SelectQueryBuilder, ): SelectQueryBuilder { const cursors: CursorParam = {}; + const clonedBuilder = new SelectQueryBuilder(builder) if (this.hasAfterCursor()) { Object.assign(cursors, this.decode(this.afterCursor as string)); @@ -124,15 +125,15 @@ export default class Paginator { } 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(