Node.js - Create Custom Function/Middleware in Express 4
|Shares :

Node.js - Create Custom Function/Middleware in Express 4

When we're creating a Route and it's Actions in Express, its recommended to separate some actions inside that route. 

for example

//Example load Users 
router.get('/users',function(req,res){
  //we can pop this query out  
  req.query("SELECT * from users",function(err,rows){
       if(rows.length){ //if users found
            res.status(200).send(rows);
}else{
         res.status(200).send("No users found in Database");
    }
     });
}); 

we can create a custom Function for the code above like this

function loadUser(req,res,next){
    
    //Rows should be a result from DB
    
    var rows = ["Nadya","Ganjar","Momon"];
    
    if(rows.length){ //if users found
        
        //assign object . accesibble on Next route
        req.user = rows;
        next();
        
    }else{
        
        res.status(200).send("No users found in Database");
    }
}

And the Route 

//Example load Users 
router.get('/users',loadUser,function(req,res){
    
    //accessing req.user
    console.log("Fetching users...",req.user); 
    res.status(200).send(req.user);
});


We can also have multiple Custom function like this

//load profile
function loadProfile(req,res,next){
    
    //Rows should be a result from DB
    
    var row = ["Nadya","Ganjar","Momon"];    
    var user_id = req.params.user_id;
    
    if(row[user_id]){ //if users found
        
        //assign object . accesibble on Next route
        req.user = row[user_id];
        next();
        
    }else{      
        res.status(200).send("No users found in Database");
    }
} //check if Admin ?
function isAdmin(req,res,next){
    console.log("Fetched user : ",req.user);
    if(req.user=="admin"){
       
       //allow next route to run
       next();   
           
    }else{        
        res.status(401).send("Permission denied. Admin Only");
    }
}


Load Profile only  ? 

//Example load User Profile
router.get('/profile/:user_id',loadProfile,function(req,res){
    
    //accessing req.user
    console.log("Fetching profile...",req.user); 
    res.status(200).send(req.user);
});


Load profile and Check if its Administrator  ? 

//Example load User Profile
router.get('/profile/:user_id',loadProfile,isAdmin,function(req,res){
    
    //accessing req.user
    console.log("Fetching profile...",req.user); 
    res.status(200).send(req.user);
});


if you look closely, i put loadProfile,isAdmin sequentially . Its because When I get the User, I need to check if the user is Admin or not. 

If we put it like this isAdmin, loadProfile  I'd not be able to check the user as the value of this

req.user

object is undefined . We need to order them in the right sequence. 


That's all. You can now create your own function/middleware to clean Up your Route.


Tags : #node.js #express-4


SHARES :


Akbar Pribadi's Avatar

A DigitalPreneur, IT Consultant
> 75% komen akan dibalas. Mohon sabar ya. Simpan halaman ini dan cek kembali lagi

Comments

* Email will not be published


    Privacy .ToS .Contact Us
    © 2017 Teknosains