Skip to content

Response Interceptor

Thiago da Rosa de Bustamante edited this page Jan 19, 2018 · 9 revisions

A Response Interceptor is a function that receives the following parameters:

  • body: the body of the response received from the destination API.
  • headers the response headers to be sent by the gateway to the client.
  • request: the request received by gateway from the client.

The interceptor must return an object containing:

Property Type Description Required
body any If provided, modify the response body. false
updateHeaders any An object contaning the headers to be added to the response. If the response already includes one of those headers, they will be overwritten. false
removeHeaders string[] A list of headers that must be suprresed from the response. false

It is also possible to return a Promise.

Each interceptor must be defined on its own .js file.

Example:

/**
 * Where request is the object created by [http](https://nodejs.org/api/http.html) module.
 * @param body the body of the response received from the destination API.
 * @param headers the response headers to be sent by the gateway to the client.
 * @param request the request received by gateway from the client.
 * @return An object that can contains: 
 *  - body: the response body,
 *  - updateHeaders: inform a list of headers to be included into the response 
 *  - removeHeaders: a list of headers to be suppressed.
 */
module.exports = function(body, headers, request) {
   var data = JSON.parse(body.toString('utf8'));
   var newHeaders = {
      mySpecialHeader: 'header value',
      myOtherSpecialHeader: 'header value 2'
   };
   return {body: data, updateHeaders: newHeaders, removeHeaders: ['excludedHeader']};
};

or

module.exports = function(body, headers, request) {
   return new Promise((resolve, reject) => {
      var data = JSON.parse(body.toString('utf8'));
      var newHeaders = {
          mySpecialHeader: 'header value',
          myOtherSpecialHeader: 'header value 2'
      };
      resolve({body: data, updateHeaders: newHeaders, removeHeaders: ['excludedHeader']});
   });
};

If the response already includes one of those headers, they will be overwritten.

You can configure a request interceptor middleware through:

  • Admin Rest API: POST /midleware/interceptors/response
  • SDK: sdk.middleware.addResponseInterceptor(name, fileName);
  • CLI: treeGatewayConfig middleware responseInterceptor -a <name> ./filename.js

Tree Gateway provide some interceptor middlewares for common tasks already included in its distribution. Check the list here.

Clone this wiki locally