Skip to content

Commit

Permalink
feat: add filters
Browse files Browse the repository at this point in the history
  • Loading branch information
tylersai committed Jan 14, 2025
1 parent d94bd46 commit 1af80cf
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 15 deletions.
10 changes: 5 additions & 5 deletions src/movie/dto/create-movie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,23 @@ class CreateMoviePayload {

@IsString()
@IsOptional()
overview: string;
overview?: string;

@IsDateString()
@IsOptional()
release_date: string;
release_date?: string;

@IsString()
@IsOptional()
poster_path: string;
poster_path?: string;

@IsNumberString()
@IsOptional()
vote_average: number;
vote_average?: number;

@IsInt()
@IsOptional()
vote_count: number;
vote_count?: number;
}

export default CreateMoviePayload;
5 changes: 3 additions & 2 deletions src/movie/movie.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Param,
Post,
Put,
Query,
} from '@nestjs/common';
import { MovieService } from './movie.service';
import CreateMoviePayload from './dto/create-movie';
Expand All @@ -16,8 +17,8 @@ export class MovieController {
constructor(private readonly movieService: MovieService) {}

@Get()
getAll() {
return this.movieService.findAll();
getAll(@Query() filters: Record<string, string>) {
return this.movieService.findAll(filters);
}

@Get(':id')
Expand Down
28 changes: 20 additions & 8 deletions src/movie/movie.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,19 @@ import UpdateMoviePayload from './dto/update-movie';
export class MovieService {
constructor(@InjectModel(Movie.name) private movieModel: Model<Movie>) {}

async findAll(): Promise<Movie[]> {
return this.movieModel.find().exec();
async findAll(filters: Record<string, string>): Promise<Movie[]> {
const query: Record<string, any> = {};
if (filters.title) {
query.title = { $regex: filters.title, $options: 'i' };
}
if (filters.overview) {
query.overview = { $regex: filters.overview, $options: 'i' };
}
if (filters.rating && filters.rating.split(':').length == 2) {
const rts = filters.rating.split(':');
query.vote_average = { [rts[0]]: rts[1] }; // $eq, $gt, $lt, $gte, $lte etc
}
return this.movieModel.find(query).exec();
}

async findById(id: string): Promise<Movie> {
Expand All @@ -36,11 +47,12 @@ export class MovieService {
}

async deleteById(id: string): Promise<RespMessage> {
const movie = await this.findById(id);
movie.deleteOne();
return {
statusCode: HttpStatus.OK,
message: 'Deleted successfully',
};
if (isValidObjectId(id)) {
await this.movieModel.deleteOne({ _id: id }).exec();
return {
statusCode: HttpStatus.OK,
message: 'Deleted successfully',
};
} else throw new NotFoundException();
}
}

0 comments on commit 1af80cf

Please sign in to comment.