I create some kind of "routing system" for RestfulAPI in function runUrl - on input I put url which contains some parameters (ID values) and I want to find this url in routes array, execute function given for that route with this parameters, and return that result as runUrl result.
function runUrl(url) {
return projects('f505ecfb74','5e735f505c'); // hardcoded mockup
// Question: how this function should look like ?
}
let routes = [
['/cars', cars ],
['/companies/:companyId/cars/:carId/projects', projects ],
['/companies/:companyId/room/:roomId', rooms ],
//...
];
// list of funtions to execute for given url
function cars() { return ["car1","car2"]; }
function projects(companyId,carId) { return [`proj-${companyId}`,`proj-${carId}`]; }
function rooms(companyId,roomId) { return `room-${companyId}-room-${roomId}` }
// ... (more functions)
// TEST
console.log(runUrl('/companies/f505ecfb74/cars/5e735f505c/projects'));
So far I write below function - but I have headache and it doesn't work
function runUrl(url) {
let route = routes.find( r=> url.match(r[0]) );
if(route) {
return route[1](url.match(route[0]));
}
return null;
}
The parameters values are alpha-numeric strings, parameters names in routes array start with : and then are alpha-numeric strings too. The number of parameters is arbitrary.
How function runUrl should look like?
routesarray unchangeable, or can you modify it?routesshould be as simple as possible so putting regexp there are not allowed