Qlik Community

Qlik Design Blog

All about product and Qlik solutions: scripting, data modeling, visual design, extensions, best practices, etc.

Employee
Employee

enigma.js interceptors

enigma.js implements an interceptor pattern that can be useful for all kinds of stuff. The basics of interceptors is that when a message is sent or received the interceptor is invoked and the message cycle suspended. Then you can perform some actions and/or modify the request or response, and then continue the message along its journey. You can find the docs for enigma.js interceptors at enigma.js interceptors.

Let's take a look at an example from the enigma.js docs which you can find at enigma.js/toggle-delta.js. This example implements a request interceptor which modifies the request and then passes it along.

onFulfilled: function toggleDelta(sessionReference, request) {
      // check if the request is something we want to modify:
      if (request.method === 'EngineVersion' && request.handle === -1) {
        // we toggle the delta protocol flag off for this request specifically:
        request.delta = false;
      }
      return request;
    },

Notice that the request is mutated, and then returned. If the request is not returned, then no message requests will make it to their destination, so remember to return the request so it can continue along.

Now let's take a look at a response interceptor example. You can find the full example at enigma.js/retry-aborted.js

onRejected: function retryAbortedError(sessionReference, request, error) {
      console.log('Request: Rejected', error);
      // We only want to handle aborted QIX errors:
      if (error.code === schema.enums.LocalizedErrorCode.LOCERR_GENERIC_ABORTED) {
        // We keep track of how many consecutive times we have tried to do this call:
        request.tries = (request.tries || 0) + 1;
        console.log(`Request: Retry #${request.tries}`);
        // We do not want to get stuck in an infinite loop here if something has gone
        // awry, so we only retry until we have reached MAX_RETRIES:
        if (request.tries <= MAX_RETRIES) {
          return request.retry();
        }
      }
      // If it was not an aborted QIX call, or if we reached MAX_RETRIES, we let the error
      // trickle down to potential other interceptors, and finally down to resolving/rejecting
      // the initial promise that the user got when invoking the QIX method:
      return this.Promise.reject(error);
    },

This interceptor is triggered when a request is rejected and retries the request a set number of times before finally returning the reject promise with the error if all the retries fail.

Does anyone have any clever things they're doing with enigma.js interceptors?