Skip to content

Request Interceptor

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

A Request Interceptor is a function that receives two an object representing the request that will be sent by the proxy, targeting the destination API.

The interceptor must return an object containing the properties that needs to be overwriten in the proxy request.

The proxy request object contains the following properties:

Property Type Description Required
body any If proxy.parseReqBody is true, contains the parsed request body. false
headers any An object contaning the headers to be added to the request. false
method string The HTTP method to be used in the proxy request. false
url string The url path of the request under the target destination API. false

It is also possible to return a Promise.

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

Example:

/**
 * Where proxyReq and userlReq are request objects created by [http](https://nodejs.org/api/http.html) module.
 * @param proxyReq the request that is being created by the proxy engine targeting the destination API.
 * @param userReq the request received by the gateway from the client.
 */
module.exports = function(proxyReq) {
   // you can update headers
   proxyReq.headers['Content-Type'] = 'text/html';
   // you can change the method
   proxyReq.method = 'GET';
   // you can munge the bodyContent.
   proxyReq.body = proxyReq.body.toString().replace(/losing/, 'winning!');

   return proxyReq;
};

or

module.exports = function(request) {
   return new Promise((proxyReq, reject) => {
      var data = JSON.parse(proxyReq.toString('utf8'));
      var newHeaders = Object.assign(request.headers, {
          mySpecialHeader: 'header value',
          myOtherSpecialHeader: 'header value 2'
      });

      resolve({body: data, headers: newHeaders, url: '/changedPath'});
   });
};

Note that to be able to access the request body, you must set the parseReqBody to true on the proxy config.

You can configure a request interceptor middleware through:

  • Admin Rest API: POST /midleware/interceptors/request
  • SDK: sdk.middleware.addRequestInterceptor(name, fileName);
  • CLI: treeGatewayConfig middleware requestInterceptor -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