Abdul Rehman Sayed Abdul Rehman Sayed - 5 months ago 13
Node.js Question

Express : Calling functions on app.param in multiple routes with same para name

I have 2 routes defined in 2 separate files but a parameter RecordId is same for both the routes:

I am expecting that whenever I call /api/CountryMaster/:RecordId,
only RecordByIdCtry function should be called. &
when I am calling /api/commonMaster/:MasterName/:RecordId,
only RecordByIdCmn function should be called.

However, both functions are getting called with the order being as set in javascript.
i.e.

require('../app/routes/commonMaster.server.routes.js')(app);
require('../app/routes/countryMaster.server.routes.js')(app);


How can i stop these & ensure that only one method is called.

//CountryMaster.js

var ctrl = require('../../app/controllers/CountryMaster.server.ctrl.js');
var users = require('../../app/controllers/user.server.ctrl.js');
module.exports = function (app)
{

app.route('/api/CountryMaster')
.get(users.requiresLogin,ctrl.list)
.post(users.requiresLogin,ctrl.create);


app.route('/api/CountryMaster/:RecordId')
.get(ctrl.read)
.put(users.requiresLogin, ctrl.hasAuthorization, ctrl.update)
.delete(users.requiresLogin, ctrl.hasAuthorization, ctrl.delete);

app.param('RecordId', ctrl.RecordByIdCtry);
}


//CommonMaster.js

var ctrl = require('../../app/controllers/commonMaster.server.ctrl.js');
var users = require('../../app/controllers/user.server.ctrl.js');
module.exports = function (app)
{
app.route('/api/commonMaster/:MasterName')
.get(users.requiresLogin,ctrl.list)
.post(users.requiresLogin,ctrl.create);
app.route('/api/commonMaster/:MasterName/:RecordId')
.get(ctrl.read)
.put(users.requiresLogin, ctrl.hasAuthorization, ctrl.update)
.delete(users.requiresLogin, ctrl.hasAuthorization, ctrl.delete);
app.param('MasterName', ctrl.MasterName);
app.param('RecordId', ctrl.RecordByIdCmn);
}


How can I ensure that only one method is called..

Answer

In your code, app is always the same app, so you're basically declaring two handlers for the same parameter, which isn't going to work.

You should use entirely separate routers instead:

// CountryMaster.js
...
module.exports = function(app) {
  var router = require('express').Router();

  router.route('/')
        .get(...)
        .post(...);

  router.route('/:RecordId')
        .get(...)
        .put(...)
        .delete(...);

  // The magic:
  router.param('RecordId', ctrl.RecordByIdCtry);

  // Mount the router on `/api/CountryMaster`
  app.use('/api/CountryMaster', router);
};

And similar for CommonMaster.js.

Comments