Created
September 17, 2021 14:53
-
-
Save j-catania/f4d39c736cae7967331cd985332a54a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Body, | |
Controller, | |
Delete, | |
Get, | |
HttpCode, | |
HttpStatus, | |
Param, | |
Patch, | |
Put, | |
Res, | |
} from '@nestjs/common'; | |
import { InjectModel } from '@nestjs/mongoose'; | |
import { Movie, MovieDocument } from '../../models/movie.schema'; | |
import { Model } from 'mongoose'; | |
import { Response } from 'express'; | |
import { ObjectId } from 'mongodb'; | |
@Controller('movies') | |
export class MoviesController { | |
constructor( | |
@InjectModel(Movie.name) private movieModel: Model<MovieDocument>, | |
) {} | |
@Get() | |
async get(): Promise<Movie[]> { | |
return this.movieModel.find().exec(); | |
} | |
@Put() | |
@HttpCode(201) | |
async create(@Body() createMovieDto: Movie) { | |
const createdMovie = new this.movieModel(createMovieDto); | |
return createdMovie.save(); | |
} | |
@Delete(':id') | |
async delete(@Param('id') id: string) { | |
return this.movieModel.deleteOne({ _id: id }); | |
} | |
@Get(':id') | |
async getById(@Param('id') id: string, @Res() res: Response) { | |
if (ObjectId.isValid(id)) { | |
const rt = await this.movieModel.findById(id); | |
return rt | |
? res.status(HttpStatus.OK).send(rt) | |
: res.status(HttpStatus.NOT_FOUND).send(); | |
} else { | |
return res.status(HttpStatus.BAD_REQUEST).send(); | |
} | |
} | |
@Patch(':id') | |
async patch(@Param('id') id: string, @Body() updateMovieDto: Movie) { | |
return this.movieModel.findByIdAndUpdate(id, updateMovieDto, { | |
new: true, | |
useFindAndModify: false, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment