Skip to content

paginate function returns wrong number of items when using queryBuilder #894

@Mnigos

Description

@Mnigos

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions