user2727195 user2727195 - 2 months ago 7
Javascript Question

differentiate between different urls

I am trying to differentiate between different urls. I have an if/else in place but hopefully this can be done better in vanilla js. No express js please.

/product
/product/1
/product/1/customer

/product
/product/2
/product/2/customer


/customer
/customer/1
/customer/1/product

/customer
/customer/2
/customer/2/product


Current strategy:

if(request.url.indexOf('/product') != -1 && request.url.length == '/product'.length) {

} else if { // /product/:id
if(!request.params) request.params = {};
request.params.id = request.url.match(/^\/product\/([^\\/]+?)(?:\/(?=$))?$/i)[1];
} else { // 3rd case /product/1/customer

}


I think my if/else are not resolving to all uri's mentioned above. Please suggest any solution, so that I can resolve all 3 cases from above in a reusable way for different urls, and run appropriate queries from there.

Answer

Here is a very basic example that will hopefully put you on the right track. You firstly need to store all the urls you want, and their associated functions that you want to run. Then when a new url comes in, you need to compare it to your stored urls to see if there is a match. As urls can have certain varying values, you need a way to deal with wildcards.

So firstly create a function that adds a particular url scheme, and associated run function to an array.

var myUrls = [];
function addUrl(url, associatedFunc){

    mrUrls.push({
        func: associatedFunc,
        parts: url.split('/').map(function(item){
            return item.startsWith(':') ? null : item;
        });
    });
}

To add a new url you would put : in front of any part of the url that can be wild.

addUlr('/product/:value/customer', doCustomerStuffFunc);

Next you need a way of comparing incoming url requests with your url array.

function resolveUrl(url){

    myUrls.forEach(function(item){
        var pieces = url.split('/');
        if(pieces.length === item.parts.length){
            for(var i=0; i<pieces.length; i++){
                // check if the piece is valid
                if(item.parts[i] && pieces[i] !== item.parts[i]){
                    break;
                }

                // if there is an exact match run the function and return
                if(i === pieces.length - 1){ return item.func(pieces); }
            }
        }
    });
}

This will run the first encountered matches associated function, passing in an array containing all the values in the given url.

Note: This is untested code, written off the top of my head, intended to get you started, and not be a full solution.