jkyberneees / fastify-gateway

A Node.js API gateway that just works!
https://www.npmjs.com/package/k-fastify-gateway
MIT License
108 stars 14 forks source link

Manipulating response in onResponse hook #64

Closed esdrasjnr closed 3 years ago

esdrasjnr commented 3 years ago

Hello, first thanks for the amazing library. 🎉

Is there any way to access the response body payload in the onResponse hook? If yes, how?

esdrasjnr commented 3 years ago

After a little investigation, I found that we could decode the response (third parameter) as a stream. My code looks like this:

const decodeResponse = async (res) => new Promise((resolve) => {
  const body = [];
  res.on('data', (chunk) => body.push(chunk)).on('end', () => resolve(JSON.parse(body.join(''))));
});

const onResponseHook = (req, reply, res) => {
  decodeResponse(res).then((payload) => { ... });
  reply.send(res);
};

References: https://nodejs.org/api/http.html https://stackoverflow.com/a/54025408