Javascript, The Builder Pattern & Callbacks

Problem

I'm trying to use Node.js to handle some scriptable URL redirection for me. It's working quite well but the scripts need to be in as simple a format as possible as it will be managed by someone else.

What I'd like to do is use the builder pattern so I can have something along the lines of:

redirectWhen.isMobileDevice().urlMatches("http://www.somewhere.com").thenGoTo("http://mobile.somewhere.com");
redirectWhen.urlMatches("http://subdomain.somewhere.com").thenGoTo("http://www.somewhere.com/somefolder/");

Then I'd redirect based on the results (basically the last one that matched all items in the chain wins). If you imagine all the functions (isMobileDevice() & urlMatches(...) do some simple string checking & nothing more, then all works fine.

But I need the isMobileDevice() function to perform an HTTP request to something. That means having a callback function that gets called when the response completes. Will it be possible to do this & still keep the builder pattern intact? I imagine I could do something like:

redirectWhen.isMobileDevice(function() {
  urlMatches("...").thenGoTo("...");
});

But that's adding more complexity to the scripts than I want to. The people who will be managing these scripts know basic JavaScript but if they have to start nesting callbacks, I imagine they will get confused fast.

I'm guessing I'm trying to achieve something that's not possible here but I don't know enough JS myself to be able to confirm that!

Problem courtesy of: Lee Theobald

Solution

You shouldn't have to give up your elegant building pattern just to make it work asynchronously. You can make a linked list of nodes with each node calling the next node when it succeeds.

I set up a fiddle using a Chain and multiple ChainNode implementations. Some notes:

  • Each ChainNode has an execute() method and a nextNode which it needs to call using next() when it is done with its own processing. For example, the URL pattern matcher calls the next node only if the URL matches the pattern, else it simply returns (breaking the chain of execution).
  • The IsMobileNode can be implemented by calling next() from a callback to some asynchronous call (such as AJAX). In the fiddle, a simple setTimeout demonstrates the concept.
  • The Chain keeps a head which indicates where the start execution and a tail on which to append new nodes. The chain(nextNode) method makes sure the chain is kept intact.
  • The urlMatches(urlPattern) and isMobileDevice() methods simply create a node and append it to the chain.
  • The thenGoTo() method chains a final node to initiate the redirect. Then, it executes the chain starting from the head.
Solution courtesy of: Mattias Buelens

Discussion

The comment by Dan Lee on my question also helped me come across the Q library: https://github.com/kriskowal/q . That certainly would help with what I wanted, although it's not as simple as the other answers.

Discussion courtesy of: Lee Theobald

It is perfectly possible; your builder returns an intermediate object at each step, and in the last step, you finally put the pieces together and call the final function.

function redirectWhen() {
    var building = {};  // saved state goes here

    // actually implement redirection
    function build() {
        // expects building = { source: "...", target: "...", mobile: optionalBoolean}            
        if (building.mobile) {
           checkMobile();
        } else {
           finishBuild();
        }
    }

    function checkMobile() {
        // check if actually mobile by making an HTTP request
        // in the success callback, calls finishBuild - fails otherwise
        // ..
    }

    function finishBuild() {
        // accessible only if mobile not requested, or if requested and mobile check passed
        // ..
    }

    // prepare the second step
    var urlMatches = function(url) {
        building.source = url;
        return { thenGoTo: function(target) { building.target = target; build(); } }
    }

    // return the next steps
    return { 
       isMobileDevice: function() { builder.mobile = true; return urlMatches; },
       urlMatches: urlMatches
    }
}

To support your mobile test, you would split build into two parts (the check, and the callback); but this would be opaque to the user, who does not even know that there is a build function anywhere.

Discussion courtesy of: tucuxi

This recipe can be found in it's original form on Stack Over Flow.