...

/

Creating the Movies Controller

Creating the Movies Controller

Let's learn how to create a controller that the route file can use to access the dao file.

In this lesson, we’ll create a controller to access the moviesDAO.js file, which we created previously.

MOVIEREVIEWS_DB_URI=mongodb+srv://admin:hello@cluster0.yjxj4.mongodb.net/sample_mflix?retryWrites=true&w=majority
MOVIEREVIEWS_NS=sample_mflix
PORT=5000
The initial files we will build on

Creating a movie controller

In the api folder, let’s create a new file movies.controller.js with the following code:

Press + to interact
import MoviesDAO from '../dao/moviesDAO.js'
export default class MoviesController{
static async apiGetMovies(req,res,next){
const moviesPerPage = req.query.moviesPerPage ?
parseInt(req.query.moviesPerPage) : 20
const page = req.query.page ? parseInt(req.query.page) : 0
let filters = {}
if(req.query.rated){
filters.rated = req.query.rated
}
else if(req.query.title){
filters.title = req.query.title
}
const { moviesList, totalNumMovies } = await MoviesDAO.getMovies({
filters,
page,
moviesPerPage
})
let response ={
movies: moviesList,
page: page,
filters: filters,
entries_per_page: moviesPerPage,
total_results: totalNumMovies
}
res.json(response)
}
}

Line 1: We first import MoviesDAO from the the dao directory.

Lines 3–6: We ...