From 65797b924343be73722bd62f8e9347ccfdda99ef Mon Sep 17 00:00:00 2001 From: Toast Date: Sun, 2 Feb 2025 18:45:36 +0100 Subject: [PATCH] Shows: add pagination to search endpoint --- src/shows/shows.controller.ts | 12 +++++++++--- src/shows/shows.service.ts | 14 +++++++++++--- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/shows/shows.controller.ts b/src/shows/shows.controller.ts index 9d06964..84d606e 100644 --- a/src/shows/shows.controller.ts +++ b/src/shows/shows.controller.ts @@ -85,15 +85,21 @@ export class ShowsController { } @Get('search') - async search(@Query() search: SearchDto) { + async search(@Query() search: SearchDto, @Query() pagination: PaginationDto) { try { const { query } = search; - const serviceResponse = await this.showsService.search(query); + const { page, limit } = pagination; + + const serviceResponse = await this.showsService.search( + query, + page, + limit, + ); if (serviceResponse.showCount > 0) { return { status: 'Ok', shows: serviceResponse.shows, - showCount: serviceResponse.showCount + showCount: serviceResponse.showCount, }; } else { throw new NotFoundException({ diff --git a/src/shows/shows.service.ts b/src/shows/shows.service.ts index b7e543b..4e7a475 100644 --- a/src/shows/shows.service.ts +++ b/src/shows/shows.service.ts @@ -32,14 +32,22 @@ export class ShowsService { return this.showModel.findById(id); } - async search(name: string) { + async search(name: string, page: number, showsPerPage: number) { const regex = new RegExp(name, 'i'); const filter = { $or: [{ title: { $regex: regex } }, { description: { $regex: regex } }], }; + let shows; + + if (showsPerPage !== undefined) { + const skip = (page - 1) * showsPerPage; + shows = await this.showModel.find(filter).skip(skip).limit(showsPerPage); + } else { + shows = await this.showModel.find(filter); + } return { - shows: await this.showModel.find(filter), - showCount: await this.showModel.find(filter).countDocuments() + shows: shows, + showCount: await this.showModel.find(filter).countDocuments(), }; }