node.js - How to handle url+multiple otpional query params in node? -


i making rest api. , have multiple optional params. here solution have taken, there solution? url can be

www.myurl.com/  

or

www.myurl.com/faqid/22 

or

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

here implementation

var getfaq = (req, res) => {     let faqdetails = faq.map(obj => obj);//it mock json     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) 

i suggest should try organise app routes in such way methods follow single responsibility principle every function write should 1 thing. should have 1 defined goal. in above getfaq seems doing many things.

you'd ideally want divide them getall(), getsingle() , gettopic() functions , delegate each responsible route:

router.get('/:faqid/topic/:topic', gettopic) router.get('/:faqid', getsingle) router.get('/', getall) 

that way it's easier unit-test , debug.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -