2

I am making a rest api. And I have multiple optional params. Here is the solution i have taken, but is there another solution? The url can be

www.myurl.com/ 

or

www.myurl.com/faqid/22

or

www.myurl.com/faqid/22/locale/english

Here is my implementation

var getFaq = (req, res) => {
    let faqDetails = FAQ.map(obj => obj);//it is a mock json for now
    faqDetails = req.params.faqid ? faqDetails.filter(obj => obj.id == req.params.faqid) : faqDetails;
    faqDetails = req.params.topic ? faqDetails.filter(obj => obj.topic == req.params.topic) : faqDetails;
    return res.status(200).send(faqDetails);
}
router.get('/:faqid/topic/:topic', getFaq)
router.get('/:faqid', getFaq)
router.get('/', getFaq)

1 Answer 1

1

I would suggest you should try to organise your app routes in such a way that methods follow the Single Responsibility Principle where every function you write should do exactly one thing. It should have one clearly defined goal. In the above getFaq seems to be doing so many things.

You'd ideally want to divide them up to getAll(), getSingle() and getTopic() functions and then delegate each to the responsible route:

router.get('/:faqid/topic/:topic', getTopic)
router.get('/:faqid', getSingle)
router.get('/', getAll)

That way it's easier to unit-test and debug.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.