diff --git a/src/pagination.dto.ts b/src/pagination.dto.ts index fbdd2e1..59c33f1 100644 --- a/src/pagination.dto.ts +++ b/src/pagination.dto.ts @@ -1,15 +1,15 @@ -import { Type } from "class-transformer"; -import { IsNumber, IsOptional, Min } from "class-validator"; +import { Type } from 'class-transformer'; +import { IsNumber, IsOptional, Min } from 'class-validator'; export class PaginationDto { @IsOptional() @IsNumber() @Type(() => Number) @Min(1) - page?: number = 1; + page?: number; @IsOptional() @IsNumber() @Type(() => Number) @Min(1) - limit?: number = 1; + limit?: number; } diff --git a/src/shows/shows.controller.ts b/src/shows/shows.controller.ts index 86e4ca1..84d606e 100644 --- a/src/shows/shows.controller.ts +++ b/src/shows/shows.controller.ts @@ -85,12 +85,22 @@ export class ShowsController { } @Get('search') - async search(@Query() search: SearchDto) { + async search(@Query() search: SearchDto, @Query() pagination: PaginationDto) { try { const { query } = search; - const shows = await this.showsService.search(query); - if (shows.length > 0) { - return { status: 'Ok', show: shows, test: shows.length }; + 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, + }; } else { throw new NotFoundException({ status: 'Error', diff --git a/src/shows/shows.service.ts b/src/shows/shows.service.ts index 76189f8..4e7a475 100644 --- a/src/shows/shows.service.ts +++ b/src/shows/shows.service.ts @@ -14,11 +14,8 @@ export class ShowsService { } 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) { + if (showsPerPage !== undefined) { const skip = (page - 1) * showsPerPage; shows = await this.showModel.find().skip(skip).limit(showsPerPage); } else { @@ -35,9 +32,23 @@ 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'); - return this.showModel.find({ title: { $regex: regex } }); + 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: shows, + showCount: await this.showModel.find(filter).countDocuments(), + }; } async update(id: string, dto: ShowDto): Promise {