router.get("customer/:customerId", async (request, response) => {
console.log("Fetch customer with a particular customer ID")
}
router.get("customer/regions", async (request, response) => {
console.log("Fetch all customers from a region")
}
But whenever I make any request the request is being served by the first api(the regions is getting considered as customerId) and not the second one.How can we have url mappings in these kind of scenarios?
You can handle this problem three ways.
One is to switch the order of your two router.get()s. Express handles them in order. The way you have it, express thinks regions is a customerId.
Another is to append a regexp to your :customerId route parameter. For example, if your customerIds are 12-digit numbers you can do this to prevent that route from handling anything except customer/123456654321-style URLs.
router.get("customer/:customerId(\d{12})", async (request, response) => {
console.log("Fetch customer with a particular customer ID")
}
A third is to use the next() parameter. It tells express that your route handler refuses the URL, and to move on to try other matching routes.
router.get("customer/:customerId(\d{12})", async (req, res, next) => {
if (<<it's an invalid customerId>>) return next()
console.log("Fetch customer with a particular customer ID")
}
You probably should use next() anyway to refuse invalid customerIds, and you should use random hard-to-guess customerId values. Because Panera Bread.