fix pagination

This commit is contained in:
hannathkadher
2025-01-08 12:16:20 +04:00
parent 0ba681d93b
commit cdba0f6554
2 changed files with 54 additions and 29 deletions

View File

@ -1,4 +1,4 @@
import { FindManyOptions, Repository } from 'typeorm';
import { FindManyOptions, Repository, SelectQueryBuilder } from 'typeorm';
import { InternalServerErrorException } from '@nestjs/common';
import { BaseResponseDto } from '../dto/base.response.dto';
import { PageResponseDto } from '../dto/pagination.response.dto';
@ -70,8 +70,8 @@ export function TypeORMCustomModel(repository: Repository<any>) {
return Object.assign(repository, {
findAll: async function (
query: Partial<TypeORMCustomModelFindAllQuery>,
customQueryBuilder?: SelectQueryBuilder<any>,
): Promise<TypeORMCustomModelFindAllResponse> {
// Extract values from the query
const {
page = 1,
size = 10,
@ -82,12 +82,7 @@ export function TypeORMCustomModel(repository: Repository<any>) {
select,
} = getDefaultQueryOptions(query);
// Ensure modelName is set before proceeding
if (!modelName) {
console.error(
'modelName is missing after getDefaultQueryOptions:',
query,
);
throw new InternalServerErrorException(
`[TypeORMCustomModel] Cannot findAll with unknown modelName`,
);
@ -96,19 +91,40 @@ export function TypeORMCustomModel(repository: Repository<any>) {
const skip = (page - 1) * size;
const order = buildTypeORMSortQuery(sort);
const relations = buildTypeORMIncludeQuery(modelName, include);
// Use the where clause directly, without wrapping it under 'where'
const whereClause = buildTypeORMWhereClause({ where });
// Ensure the whereClause is passed directly to findAndCount
const [data, count] = await repository.findAndCount({
where: whereClause,
take: size,
skip: skip,
order: order,
select: select,
relations: relations,
});
let data: any[] = [];
let count = 0;
if (customQueryBuilder) {
const qb = customQueryBuilder.skip(skip).take(size);
if (order) {
Object.keys(order).forEach((key) => {
qb.addOrderBy(key, order[key]);
});
}
if (whereClause) {
qb.where(whereClause);
}
if (select) {
const selectColumns = Array.isArray(select)
? select
: Object.keys(select).map(
(key) => `${customQueryBuilder.alias}.${key}`,
);
qb.select(selectColumns as string[]);
}
[data, count] = await qb.getManyAndCount();
} else {
[data, count] = await repository.findAndCount({
where: whereClause,
take: size,
skip: skip,
order: order,
select: select,
relations: relations,
});
}
const paginationResponseDto = getPaginationResponseDto(count, page, size);
const baseResponseDto: BaseResponseDto = {