BackendStack21/fast-gateway

Modify response body

Closed this issue · 2 comments

Hello,

I need to encrypt the response from the services but I cannot find a way to access the response body to modify it and create a new encrypted body.

I try with hooks, onResponse:

const gateway = require('fast-gateway');
const bodyParser = require('body-parser');
const Cors = require('cors');

const server = gateway({
    middlewares: [
    Cors(),
    bodyParser.json()
  ],
  routes: [{
    prefix: '/services',
    prefixRewrite: 'services',
    methods: ['POST'],
    target: 'http://localhost:9001',
    hooks: {
      onResponse(req, res, stream) {
        res.statusCode = stream.statusCode;
        // encrypt body ?
        pump(stream, res);
      }
    }
  }]
});

Please, can you help me.

Hi @maxmartinezc, thanks for reaching out.

It is actually pretty simple, here I describe an example that you will be able to adapt according to your needs:

const toArray = require('stream-to-array')
const gateway = require('fast-gateway')

gateway({
  routes: [{
    prefix: '/httpbin',
    target: 'https://httpbin.org',
    hooks: {
      async onResponse (req, res, stream) {
        // collect all streams parts
        const resBuffer = Buffer.concat(await toArray(stream))

        // parse response body, for example: JSON
        const payload = JSON.parse(resBuffer)
        // modify the response, for example adding new properties
        payload.newProperty = 'post-processing'

        // stringify response object again
        const newResponseData = JSON.stringify(payload)

        // set new content-length header
        res.setHeader('content-length', '' + Buffer.byteLength(newResponseData))
        // set response statusCode
        res.statusCode = stream.statusCode

        // send new response payload
        res.end(newResponseData)
      }
    }
  }]
}).start(8080)

Please let me know if this works for you?

Best Regards,
Rolando

It's works for me. I added a "if else flow" when body is empty.

const onResponse = async (req, res, stream) => {
  const resBuffer = Buffer.concat(await toArray(stream));
  res.statusCode = stream.statusCode;

  if (resBuffer.length > 0) {
    const encrypted = encrypt('secret', resBuffer); //encrypt function example

    const newResponseData = JSON.stringify({ data: encrypted });

    res.setHeader('content-length', '' + Buffer.byteLength(newResponseData));
    res.end(newResponseData);
  } else {
  // body is empty
    res.end();
  }
};

Thanks a lot.