Compare commits

...

5 commits

3 changed files with 35 additions and 14 deletions

View file

@ -1,15 +1,15 @@
import { Type } from "class-transformer"; import { Type } from 'class-transformer';
import { IsNumber, IsOptional, Min } from "class-validator"; import { IsNumber, IsOptional, Min } from 'class-validator';
export class PaginationDto { export class PaginationDto {
@IsOptional() @IsOptional()
@IsNumber() @IsNumber()
@Type(() => Number) @Type(() => Number)
@Min(1) @Min(1)
page?: number = 1; page?: number;
@IsOptional() @IsOptional()
@IsNumber() @IsNumber()
@Type(() => Number) @Type(() => Number)
@Min(1) @Min(1)
limit?: number = 1; limit?: number;
} }

View file

@ -85,12 +85,22 @@ export class ShowsController {
} }
@Get('search') @Get('search')
async search(@Query() search: SearchDto) { async search(@Query() search: SearchDto, @Query() pagination: PaginationDto) {
try { try {
const { query } = search; const { query } = search;
const shows = await this.showsService.search(query); const { page, limit } = pagination;
if (shows.length > 0) {
return { status: 'Ok', show: shows, test: shows.length }; const serviceResponse = await this.showsService.search(
query,
page,
limit,
);
if (serviceResponse.showCount > 0) {
return {
status: 'Ok',
shows: serviceResponse.shows,
showCount: serviceResponse.showCount,
};
} else { } else {
throw new NotFoundException({ throw new NotFoundException({
status: 'Error', status: 'Error',

View file

@ -14,11 +14,8 @@ export class ShowsService {
} }
async findAll(page: number, showsPerPage: number): Promise<any> { async findAll(page: number, showsPerPage: number): Promise<any> {
// 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; let shows;
if (showsPerPage != 1) { if (showsPerPage !== undefined) {
const skip = (page - 1) * showsPerPage; const skip = (page - 1) * showsPerPage;
shows = await this.showModel.find().skip(skip).limit(showsPerPage); shows = await this.showModel.find().skip(skip).limit(showsPerPage);
} else { } else {
@ -35,9 +32,23 @@ export class ShowsService {
return this.showModel.findById(id); return this.showModel.findById(id);
} }
async search(name: string) { async search(name: string, page: number, showsPerPage: number) {
const regex = new RegExp(name, 'i'); 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<any> { async update(id: string, dto: ShowDto): Promise<any> {