Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Mnigos opened this issue Apr 17, 2024 · 0 comments
Open

Comments

@Mnigos
Copy link

Mnigos commented Apr 17, 2024

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 Mnigos changed the title paginate function returns wrong number of items paginate function returns wrong number of items when using queryBuilder Apr 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant