Sunday, March 5, 2017

Custom middleware in Node


Middleware would inject between the call and the Route.

  • When a client sends a request, it is handled by the route in the router
  • This router would send a response back to the client
  • When we have a middleware it would take the request process it and and then forward that request to the route. Then the route would send the response to the client

Custom middleware to find the user based on the ID


//Load the model for users
User=require('./models/user');
//Custom middleware to find if user exists
app.use('/api/Users/:_id',function(req,res,next){
  console.log('custom middleware');
      //Find based on ID
       User.findById(req.params._id, function(err, user) {
             if (err)
                res.status(500).send(err);
              //fetch user and send it to next function
             else if(user)
             {
                    req.user=user;
               next();
             }
            else
            {
              res.status(404).send('no book found');
            }
        });
});

Use the middleware in the route for get operation

//Get specific record
  app.get("/api/Users/:_id",function(req,res){
      //use custom middleware
       res.json(req.user)
  });

Use the middleware in the route for put operation

/**
  * PUT
*/
  app.put('/api/Users/:_id',function(req,res){
      //use custom middleware tp fetch the document
        req.user.firstName=req.body.firstName;
        req.user.lastName=req.body.lastName;
        req.user.save();
        res.json(req.user);
    });

Output of this route

No comments:

Post a Comment