JavaScript Mapper for RESTFul Methods

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:

"rest/user/get/my"

… We can execute:

window.mapper.userGetMy();

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

window.mapper.userGetMy({
    firstName: "John",
    lastName: "Smith",
    id: 9999
});

… Which will result in an ajax request to:

rest/user/get/?firstName=John&lastName=Smith&id=9999&_=1348612389319

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):

(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"
            }
        }
    );
})();

The above code can be tested like this:

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

Below is the full source code of the RestMethodMapper class:

(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;
})();

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

Advertisements

15 comments

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s