Question

I'm working on porting the UI of an existing application from GWT to Backbone. The backend stays the same. All requests in the backend are handled by a single endpoint. URL-encoded parameters determine what the response should be. For instance:

http://localhost/adminNPS?request=getDashboard&object=dash&id=2
http://localhost/adminNPS?request=getDashboard&object=dash&id=3
http://localhost/adminNPS?request=saveDashboard&object=dash&id=1 ... {json}
http://localhost/adminNPS?request=getUser&object=user
http://localhost/adminNPS?request=createUser&object=user ... {json}
http://localhost/adminNPS?request=getUserPermissions&object=user

Don't ask who devised this scheme =P.. Now, I have to design Backbone Models / Collections to connect to this endpoint and use mockjax to simulate the ajax calls as well.. So I have two questions now.

  1. How do I create mock calls for this in mockjax? Using something like follows works fine.. But requires the precise order of parameters in URL.. mockjax's documentation states parameters can be matched with data: { key: value } hash.. But this doesn't work for me.. Can someone guide me further on this?

    $.mockjax({
        url: http://localhost/adminNPS?request=getDashboard&object=dash&id=2,
        responseText: { ... }
    });
    
  2. How should the models be coded such that, for instance, DashboardModel accesses http://localhost/adminNPS?request=getDashboard&object=dash&id=3 when fetched and http://localhost/adminNPS?request=saveDashboard&object=dash&id=3 when saving..

Was it helpful?

Solution

With regard to matching the query parameters using the data option, this is a documented bug in Mockjax. Basically, the request matcher only works with data objects on the $.ajax() call, not query strings.

That said, there are two ways you could handle this:

1) you could use the regex version of the url matcher:

$.mockjax({
  url: /adminNPS?request=[^&]+&object=[^&]+&id=[0-9]+/i, // tweak to your needs
  ...
});

2) or you could use the fully custom matching ability by passing in a function:

$.mockjax(function(settings) {
  // examine `settings.url` which would be something like:
  // http://localhost/adminNPS?request=getDashboard&object=dash&id=2

  var q = settings.url.split('?')[1].split('&');
  var data = {}; // will be a hash of the query data
  for (var i=0, l=q.length; i<l; ++i) {
    data[q[i].split('=')[0]] = q[i].split('=')[1];
  }

  // Now you can look at the `data` object to do your matching

  if ( /* the URL matches what you want */ ) {
    return {
      response: function () {
        this.responseText = { ... }; /* whatever you want the response to be */
      }
    };
  }
  return; // no match
});

Updated to show how you might investigate the query string...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top