1

I am building a RESTful API using expressJS, In my controller I have several functions like Chall_1, Chall_2,...

exports.validateChall_1 = function(res) {
//logic
  res.json(1);
};
exports.validateChall_2 = function(res) {
    res.json(2);
};
exports.validateChall_3 = function(res) {
    res.json(3);
};

in my router.js I want to route the URL to a specific function based on challId which is a parameter in url

'use strict';
module.exports = function(app) {
  var jsvalidator = require('../controllers/jsvalidatorController');
  app.route('/chall/:challId')
    .get(/*jsvalidator.validateChall_ + req.params.challId*/);
};

Is it possible to route directly to a specific function based on challId parameter?

1 Answer 1

1

you could do something like

app.route('/chall/:challId')
  .get(function (req, res, next) {
      switch (req.params.challId) {
        case 1:
         ctrl.validate_chall1(req, res, next);
         break;
        case 2:
         ctrl.validate_chall2();
         break;
        default:
         next() //it should continue to 404 route
         break;
  }
});

but I think doing this is better to keep the routes clean

app.route('/chall/challId/validate')
   .get(ctrl.validate)

//in ctrl 
function validate(req, res, next){
  if(req.params.challId === 1)
    validate_ctrl1()
  //etc
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.