0

My goal is to manipulate the response payload after the response already returned to the client, but it looks impossible doing it with fastify + fastify-reply-from without affecting the response time. Here is the only way I could get the response body, and do something with it.

  fastify.addHook('onSend', async (req, reply, payload) => {
return new Promise((resolve, reject) => {
  const chunks = [];

  payload.on('error', reject);
  
  payload.on('data', (chunk) => {
    chunks.push(chunk);
  });

  payload.on('end', () => {
    const body = Buffer.concat(chunks);
    doSomethingWithBody(body);

    resolve(body);
  });
});

Are there other ways to do it, without handling manually the stream (payload is "IncomingMessage" instance)?

user3164429
  • 140
  • 1
  • 10
  • Your solution is fine, and you can't avoid handling the stream since you need to change it – Manuel Spigolon Nov 26 '20 at 12:53
  • Thanks, I thought maybe I can somehow "duplicate" the stream, so one of it will go as a response to the client, another one will be handled for internal use ( e.g logging) – user3164429 Nov 29 '20 at 10:39

0 Answers0