A case of using constant file in javaScript Appliactions :Reducing coupling between frontend and backend

Problem :
If we have a REST “getBookInfo” and its response was :

{
    "book": {
        "name": "Ramayan",
        "author": "Valmiki"
    }
}

Now it’s changed to (note first the capital letters ):

{
    "Book": {
        "Name": "Ramayan",
        "Author": "Valmiki"
    }
}

So where ever we were accessing the response like below it would stop working :

_implGetBookInfoSuccess : function(data, response) {
                     var varBookInfo = response.book;
                     if (!_.isUndefined(varBookInfo)) {
                                         this._implInvokeGetBookPrice(varBookInfo.name, varBookInfo.author);
                     }
              },

Sometimes we deal with the same REST response in many files so in above scenario we had to change every file which was dealing with response and it is very difficult.

Suggested Solution :

Create a constant mapper file BookInfoResponseMapper.js :

		
define([], function() {
       var BookInfoResponseMapper = {
                     
              //CheckCoverage REST response object attribute
              Book : 'book',
                     
              //CheckCoverage REST response object attribute
              Book_Name: 'name',
                     
              //CheckCoverage REST response object attribute
              Book_Author: 'author',
       };
       return BookInfoResponseMapper;
});

Access the response attribute like below :

_ implGetBookInfoSuccess: function(data, response) {
                     var varBookInfo = response[BookInfoResponseMapper.Book];
                     if (!_.isUndefined(varBookInfo)) {
                            this._ implInvokeGetBookPrice(varBookInfo[BookInfoResponseMapper.Book_Name],
                                 varBookInfo[BookInfoResponseMapper.Book_Author]);
                           }
              }

It would reduce the coupling between FE and REST response and changing only the constant file will be sufficient in the case of any changes in REST response.

Note : Please note that all the examples above are with require.js and Backbone. But the concept can be used with any application.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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