Leaving Movie Reviews
Let's learn how to add reviews using the POST, PUT, and DELETE methods.
We'll cover the following...
In this lesson, we’ll learn how to leave reviews for movies.
MOVIEREVIEWS_DB_URI=mongodb+srv://admin:hello@cluster0.yjxj4.mongodb.net/sample_mflix?retryWrites=true&w=majority MOVIEREVIEWS_NS=sample_mflix PORT=5000
So let’s create the routes to post
, put
, and delete
reviews. The post
method is for creating a review, put
is for editing a review, and delete
is for deleting reviews. In the route file movies.route.js
, let’s add the routes, as shown below:
import express from 'express'import MoviesController from './movies.controller.js'import ReviewsController from './reviews.controller.js'const router = express.Router()router.route('/').get((req,res) => res.send(MoviesController.apiGetMovies))router.route("/review").post(ReviewsController.apiPostReview).put(ReviewsController.apiUpdateReview).delete(ReviewsController.apiDeleteReview)export default router
Line 3: We import the ReviewsController
, which we’ll create later.
Lines 6–11: We then add a /review
route that handles post
, put
, and delete
HTTP requests within this one route
call. That is to say, if the /review
route receives a post
HTTP request to add a review, we call apiPostReview
. If /review
receives a put
HTTP request to edit a review, we call apiUpdateReview
. Finally, if /review
receives a delete
HTTP request to delete a review, we call apiDeleteReview
.
Creating the review controller
Next, let’s create reviews.controller.js
with the following code:
import ReviewsDAO from '../dao/reviewsDAO.js'export default class ReviewsController{static async apiPostReview(req,res,next){try{const movieId = req.body.movie_idconst review = req.body.reviewconst userInfo = {name: req.body.name,_id: req.body.user_id}const date = new Date()const ReviewResponse = await ReviewsDAO.addReview(movieId,userInfo,review,date)res.json({ status: "success "})}catch(e){res.status(500).json({ error: e.message})}}static async apiUpdateReview(req,res,next){try{const reviewId = req.body.review_idconst review = req.body.reviewconst date = new Date()const ReviewResponse = await ReviewsDAO.updateReview(reviewId,req.body.user_id,review,date)var { error } = ReviewResponseif(error){res.status.json({error})}if(ReviewResponse.modifiedCount === 0){throw new Error ("unable to update review. User may not be original poster")}res.json({ status: "success "})}catch(e){res.status(500).json({ error: e.message})}}static async apiDeleteReview(req,res,next){try{const reviewId = req.body.review_idconst userId = req.body.user_idconst ReviewResponse = await ReviewsDAO.deleteReview(reviewId,userId,)res.json({ status: "success "})}catch(e){res.status(500).json({ error: e.message})}}}
Line 1: We first import ReviewsDAO
, which we’ll create later.
Lines 4–11: We get ...