nestjs-typeorm-paginate icon indicating copy to clipboard operation
nestjs-typeorm-paginate copied to clipboard

paginate function returns wrong number of items when using queryBuilder

Open Mnigos opened this issue 10 months ago • 5 comments

While the limit is set to 10, paginate function returns only 3 items:

{
  "items": [...],
  "meta": {
    "totalItems": 32,
    "itemCount": 3,
    "itemsPerPage": 10,
    "totalPages": 4,
    "currentPage": 1
  }
}

I tried to set limit to 20 and then paginate function returns only 6 items:

{
  "items": [...],
  "meta": {
    "totalItems": 32,
    "itemCount": 6,
    "itemsPerPage": 20,
    "totalPages": 2,
    "currentPage": 1
  }
}

On second page the number of items with limit set to 10 it still remains 3, but if I set the limit to 20 it will return 4 items:

{
  "items": [...],
  "meta": {
    "totalItems": 32,
    "itemCount": 4,
    "itemsPerPage": 20,
    "totalPages": 2,
    "currentPage": 2
  }
}

artists.controller.ts

@Controller('artists')
export class ArtistsController {
  constructor(private readonly artistsRepository: ArtistsRepository) {}

  @Get()
  async getArtists(
    @Query() { limit = 10, page = 1 }: PaginatedQuery,
  ) {
    const queryBuilder = this.artistsRepository.createQueryBuilder('a')

    queryBuilder
      .leftJoinAndSelect('a.images', 'images')
      .orderBy('a.name', 'DESC')

    return paginate(queryBuilder, { limit, page })
  }
}

paginated-query.dto.ts

export abstract class PaginatedQuery {
  @IsInt()
  @Min(1)
  @Max(50)
  @IsOptional()
  @Transform(({ value }) => (value ? Number.parseInt(value) : 10))
  limit?: number

  @IsInt()
  @Min(1)
  @IsOptional()
  @Transform(({ value }) => (value ? Number.parseInt(value) : 1))
  page?: number
}

I also have another controller that uses paginate function, but there the numbers of itemCount are different, 7 instead of 6 while limit is set to 20.

package.json

{
  "dependencies": {
    "@nestjs/core": "^10.3.0",
    "@nestjs/common": "^10.3.0",
    "@nestjs/typeorm": "10.0.1",
    "nestjs-typeorm-paginate": "4.0.4",
    "pg": "8.11.3",
    "typeorm": "0.3.19"
  }
}

EDIT: I've discovered that if you pass repository instead of queryBuilder it will return correct number of items.

Mnigos avatar Apr 17 '24 15:04 Mnigos

any news?

Mnigos avatar Jun 03 '24 17:06 Mnigos

I have same error. I think it count relationship itmes count. (.leftJoinAndSelect('a.images', 'images'))

Aung-Zaw-Phyo avatar Aug 13 '24 09:08 Aung-Zaw-Phyo

Aung

Since there is no response from contributors I decided to migrate to nestjs-paginate

Mnigos avatar Aug 15 '24 15:08 Mnigos

Aung

Since there is no response from contributors I decided to migrate to nestjs-paginate

Yes, me too

Aung-Zaw-Phyo avatar Aug 16 '24 11:08 Aung-Zaw-Phyo