How we’re using AmplifyJs

AmplifyJs is a very nice library for wrapping and handling ajax calls and other data operations. It handles requests, storing object locally, and a very nice pub-sub system. We abstracted out all of our ajax requests to use amplify, and it’s paid off hugely for us. This post is not meant to be a tutorial on how to use Amplify, but a few things we stumbled upon that is very useful.

Replace the Default Decoder

This was one of the first things we did.  We wanted to be able to handle requests that error’d in one place, so by replacing the default decoder, we were able to display a nice message to our users, yet still pass through our success data (this code is in TypeScript):

amplify.request.decoders._default = function (data, status, xhr, success, error) {
  if (data.status == "success") {
    success(data.data);
  } else {
    try {
      if (data.message == 'ValidationErrors') {
         showValidationErrors(data.failureMessages);
      } else {
       messageHub.showError(data.message);
      }
    } catch (err) {
      messageHub.showError("There was an unspecified problem with the request");
    }
    error(data);
  }
 }

Subscribe to Ajax Events

Another thing we wanted to only handle in one place was the display of a loading animation or message.  Amplify made this incredibly easy through it’s pub / sub functionality.  I was able to subscribe to two events that would track how many requests were currently happening, and show or hide a dialogue box accordingly:

 
amplify.subscribe("request.before.ajax", () => {
  if (requestsHappening == 0) {
    load.showLoading();
  }
  requestsHappening++;
});

amplify.subscribe("request.complete", () => {
  requestsHappening--;
  if (requestsHappening == 0) {
    load.hideLoading();
  }
});

This greatly simplified our request code.  We took both of these pieces of code, and called it amplify_config.js.  That got included in our bundled scripts, and it provided a nice central location to define our requests as well.  I highly recommend this as a way to simplify your ajax code, even if you’re not using the more advanced features of the library.