JavaScript Mapper for RESTFul Methods

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

Recently I had to work with a bunch of RESTFul API methods, so instead of defining manually separate calls/methods for each API request, I decided to do it viceversa – to force JavaScript to create these methods automatically for me out of the RESTFul API by providing the URLS and other required data. In short – we provide a REST end-point and a key/value map of all API methods, which we plan to use, along with their data types, request type and callback functions, which is then processed by the RestMethodMapper class and converted on the fly to pure JavaScript methods to that class, so instead of calling:

[sourcecode language=”javascript”]
"rest/user/get/my"
[/sourcecode]

… We can execute:

[sourcecode language=”javascript”]
window.mapper.userGetMy();
[/sourcecode]

… And we can also pass as an argument the http parameters object:

[sourcecode language=”javascript”]
window.mapper.userGetMy({
    firstName: "John",
    lastName: "Smith",
    id: 9999
});
[/sourcecode]

… Which will result in an ajax request to:

[sourcecode language=”javascript”]
rest/user/get/?firstName=John&lastName=Smith&id=9999&_=1348612389319
[/sourcecode]

The API methods are defined in the constructor of the RestMethodMapper class like this – the first argument is the REST end-point, the second argument is a key/value object map of all RESTFul method and their properties (type, dataType, success and failure callbacks):

[sourcecode language=”javascript”]
(function() {
    window.mapper = new AcidJs.RestMethodMapper(
        "rest/",
        {
            "user/get/": {
                type: "GET",
                cache: false,
                success: function(response) {
                    console.log("success:", response);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log("error: ", jqXHR, textStatus, errorThrown);
                },
                dataType: "json"
            },
            "user/get/my/": {
                type: "get",
            },
            "msg/post/new/": {
                type: "post"
                success: function() { },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log("error: ", jqXHR, textStatus, errorThrown);
                },
                dataType: "json"
            }
        }
    );
})();
[/sourcecode]

The above code can be tested like this:

[sourcecode language=”javascript”]
window.mapper.userGet({
    firstName: "John",
    lastName: "Smith",
    id: 9999
}); // which will request rest/user/get/ with the parameters set as an argument object
window.mapper.userGetMy(); // which will request reset/user/get/my/
window.mapper.msgPostNew({
    id: 1234,
    body: "Lorem ipsum dolot sit amet"
}); // which will request rest/msg/post/new/ with the parameters set as an argument object
[/sourcecode]

Below is the full source code of the RestMethodMapper class:

[sourcecode language=”javascript”]
(function() {
    "use strict";

    /*
     * @namespace AcidJs
     **/
    if(undefined === window.AcidJs) {
        window.AcidJs = {};
    }

    /*
     * @class RestMethodMapper
     * @constructor
     * @param endpoint {String} [optional]
     * @param method {String} rest api method, for example "user/get/my"
     * @author Martin Ivanov http://acidjs.wemakesites.net
     **/
    function RestMethodMapper(endpoint, method) {
       endpoint = endpoint || "";
       method = method || {};

       var
           that = this;

       $.each(method, function(key, value) {
           (function() {
               var
                   name = that.restToMethod(key);

               if(!that[name]) {
                   var
                       ajaxConfig = {
                           url: endpoint + key
                       };

                   if(value) {
                       $.each(value, function(k, v) {
                           ajaxConfig[k] = v;
                       });
                   }

                   that[name] = function(data) {
                       if(data) {
                           ajaxConfig.data = data;
                       }
                       $.ajax(ajaxConfig);
                   };
                }
            })();
        });
    }

    RestMethodMapper.prototype = {
        /*
         * @method restToMethod convert RESTFul api method to a JavaScript method
         * @param url {String}
         * @return {String}
         **/
        restToMethod: function(url){
            if(!url) {
                return "";
            }

            var
                path = url.split("/"),
                methodName = "";

            for(var i = 0, len = path.length; i < len; i++) {
                methodName += (i === 0) ? path[i] : path[i].charAt(0).toUpperCase() + path[i].substr(1);
            }

            return methodName;
        }
    };

    window.AcidJs.RestMethodMapper = RestMethodMapper;
})();
[/sourcecode]

The RestMethodMapper class uses jQuery, but obviously it can be easily implemented in pure JavaScript or with the help any other JavaScript library. I utilized jQuery, because the project required it, so I made use of that library’s $.ajax() method.

Related Posts

Categories and Tags
Links

© 2006 - 2018 Martin Ivanov