Extracting functions to reusable middleware

We can use our anonymous or named functions as middleware. To do so, we would export our functions by calling module.exports in routes/actors.js and routes/movies.js:

Let's take a look at our routes/actors.js file. At the top of this file, we require the Mongoose schemas we defined before:

var Actor = require('../models/actor'),

This allows our variable actor to access our MongoDB using mongo functions such as find(), create(), and update(). It will follow the schema defined in the file /models/actor.

Since actors are in movies, we will also need to require the Movie schema to show this relationship by the following.

var Movie = require('../models/movie'),

Now that we have our schema, we can begin defining the logic for the functions we described in endpoints. For example, the endpoint GET /actors/:id will retrieve the actor with the corresponding ID from our database. Let's call this function getOne(). It is defined as follows:

getOne: function(req, res, next) { Actor.findOne({ id: req.params.id })
.populate('movies')
.exec(function(err, actor) {
if (err) return res.status(400).json(err); if (!actor) return res.status(404).json(); res.status(200).json(actor);
});
},

Here, we use the mongo findOne() method to retrieve the actor with id: req.params.id. There are no joins in MongoDB so we use the .populate() method to retrieve the movies the actor is in.

The .populate() method will retrieve documents from a separate collection based on its ObjectId.

This function will return a status 400 if something went wrong with our Mongoose driver, a status 404 if the actor with :id is not found, and finally, it will return a status 200 along with the JSON of the actor object if an actor is found.

We define all the functions required for the actor endpoints in this file. The result is as follows:

// /src/routes/actors.js
var Actor = require('../models/actor'), 
var Movie = require('../models/movie'),

module.exports = {

  getAll: function(req, res, next) { 
    Actor.find(function(err, actors) {
      if (err) return res.status(400).json(err);

      res.status(200).json(actors); 
    });
  },


  createOne: function(req, res, next) { 
  Actor.create(req.body, function(err, actor) {
    if (err) return res.status(400).json(err);

    res.status(201).json(actor); 
  });
  },


  getOne: function(req, res, next) { 
    Actor.findOne({ id: req.params.id })
    .populate('movies')
.exec(function(err, actor) {
      if (err) return res.status(400).json(err); 
      if (!actor) return res.status(404).json();

      res.status(200).json(actor);
    });
  },


  updateOne: function(req, res, next) { 
    Actor.findOneAndUpdate({ id: req.params.id }, req.body,function(err, actor) {
      if (err) return res.status(400).json(err); 
      if (!actor) return res.status(404).json();

      res.status(200).json(actor); 
    });
  },


  deleteOne: function(req, res, next) { 
    Actor.findOneAndRemove({ id: req.params.id }, function(err) {
      if (err) return res.status(400).json(err);

      res.status(204).json(); 
    });
  },


  addMovie: function(req, res, next) {
    Actor.findOne({ id: req.params.id }, function(err, actor) { 
      if (err) return res.status(400).json(err);
      if (!actor) return res.status(404).json();

      Movie.findOne({ id: req.body.id }, function(err, movie) {
        if (err) return res.status(400).json(err);
        if (!movie) return res.status(404).json();

        actor.movies.push(movie); 
        actor.save(function(err) {
          if (err) return res.status(500).json(err);

          res.status(201).json(actor); 
        });
       })
     });
  },


  deleteMovie: function(req, res, next) {
    Actor.findOne({ id: req.params.id }, function(err, actor) { 
      if (err) return res.status(400).json(err);
      if (!actor) return res.status(404).json();

      actor.movies = []; 
      actor.save(function(err) {
        if (err) return res.status(400).json(err);

        res.status(204).json(actor);
      })
    });
   }

  };

For all of our movie endpoints, we need the same functions but applied to the movie collection.

After exporting these two files, we require them in app.js (/src/lib/app.js) by simply adding:

require('../routes/movies'), require('../routes/actors'),

By exporting our functions as reusable middleware, we keep our code clean and can refer to functions in our CRUD calls in the /routes folder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.38.210