1

I have 4 controllers for 4 different situations. I am trying to call the 4 controllers from the same endpoint depending on the different request queries. I have implemented the logic as below:

const express = require('express');
const quesController = require('../controllers/quesController');

const router = express.Router();

router.route('/').get((req, res) => {
    const topic = req.query.topic.toLowerCase();
    const difficulty = req.query.difficulty.toLowerCase();

    if (topic === 'random' && difficulty === 'random') {
        quesController.getQuestionRandom(req, res);
    } else if (topic === 'random') {
        quesController.getQuestionByDiff(req, res);
    } else if (difficulty === 'random') {
        quesController.getQuestionByTopic(req, res);
    } else {
        quesController.getSpecificQuestion(req, res);
    }
});

module.exports = router;

Is there any other way to do this type of conditional routing?

Rounak
  • 85
  • 2
  • 7
  • Nothing wrong here, You can handle conditions inside the controller instead of a router. just keep business logic away from routing. – Rahul Sharma Jan 31 '22 at 12:50
  • I would use res.redirect, to redirect to the correct endpoint, based in the conditionals which can be declared on a middleware or in route handler. – Andres Rene Gutierrez T Jan 31 '22 at 13:48
  • @RahulSharma thanks for the suggestion. I get confused when it comes to differentiating the business logic – Rounak Jan 31 '22 at 15:03
  • @AndresReneGutierrezT it will very helpful if you add one example in the answer – Rounak Jan 31 '22 at 15:04

1 Answers1

0

this is the example that you requested.

const express = require('express');
const quesController = require('../controllers/quesController');

const router = express.Router();
router.get('/topic-and-difficulty-random', quesController.getQuestionRandom);
router.get('/topic-random', quesController.getQuestionByDiff);
router.get('/difficulty-random', quesController.getQuestionByTopic)
router.get('/other-case', quesController.getSpecificQuestion)
router.get('/', (req, res) => {
    const topic = req.query.topic.toLowerCase();
    const difficulty = req.query.difficulty.toLowerCase();

    if (topic === 'random' && difficulty === 'random') {
        return res.redirect('/topic-and-difficulty-random');
    } else if (topic === 'random') {
        return res.redirect('/topic-random');
    } else if (difficulty === 'random') {
        return res.redirect('/difficulty-random');
    } else {
        return res.redirect('/other-case');
    }
});

module.exports = router;

With this approach you generate specific endpoint for each case and the main route is in charge of redirecting to the specific endpoint based on conditionals, this approach promotes the reuse if you want to access to the specific endpoint in your client directly.