From a2b747a82360f9c11c56b3f9a7f75790d016612e Mon Sep 17 00:00:00 2001 From: Toast Date: Sat, 1 Feb 2025 20:24:45 +0100 Subject: [PATCH] Shows: add pagination to findAll --- src/shows/shows.controller.ts | 12 +++++++++--- src/shows/shows.service.ts | 18 ++++++++++++++++-- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/shows/shows.controller.ts b/src/shows/shows.controller.ts index 7924d92..8215fa6 100644 --- a/src/shows/shows.controller.ts +++ b/src/shows/shows.controller.ts @@ -13,6 +13,7 @@ import { } from '@nestjs/common'; import { ShowsService } from './shows.service'; import { ShowDto } from './dto/show.dto'; +import { PaginationDto } from 'src/pagination.dto'; @Controller('shows') export class ShowsController { @@ -36,10 +37,15 @@ export class ShowsController { } @Get() - async findAll() { + async findAll(@Query() pagination: PaginationDto) { try { - const shows = await this.showsService.findAll(); - return { status: 'Ok', shows, totalShows: shows.length }; + const { page, limit } = pagination; + const serviceResponse = await this.showsService.findAll(page, limit); + return { + status: 'Ok', + shows: serviceResponse.shows, + showCount: serviceResponse.showCount, + }; } catch (error) { throw new InternalServerErrorException({ status: error.name, diff --git a/src/shows/shows.service.ts b/src/shows/shows.service.ts index 0c28442..76189f8 100644 --- a/src/shows/shows.service.ts +++ b/src/shows/shows.service.ts @@ -13,8 +13,22 @@ export class ShowsService { return show.save(); } - async findAll(): Promise { - return this.showModel.find(); + async findAll(page: number, showsPerPage: number): Promise { + // Default value is 1 and I can't think any reason why you would want + // a single item per page, so if showsPerPage is 1 then just don't do + // any pagination at all + let shows; + if (showsPerPage != 1) { + const skip = (page - 1) * showsPerPage; + shows = await this.showModel.find().skip(skip).limit(showsPerPage); + } else { + shows = await this.showModel.find(); + } + const total = await this.showModel.countDocuments(); + return { + shows: shows, + showCount: total, + }; } async findId(id: string): Promise {