fastify-reply-from icon indicating copy to clipboard operation
fastify-reply-from copied to clipboard

Rewrite body

Open advany opened this issue 2 years ago • 4 comments

I use @fastify/http-proxy and it works wonderfully (and faster then http-proxy-middleware). The only thing I can't figure out how can I rewrite the body of a response? I need to change the html before is send back to the client.

advany avatar Aug 08 '22 21:08 advany

use onResponse: https://github.com/fastify/fastify-reply-from#onresponserequest-reply-res

mcollina avatar Aug 09 '22 06:08 mcollina

For anyone else having this problem. I created this function and it solved it:

function change_body(request, reply, res, call_back) {
  let headers = reply.getHeaders();
  let contenttype = headers['content-type'];
  let contentencoding = headers['content-encoding'];

  if(contenttype.includes('text')) {
    let decompress;

    switch (contentencoding) {
      case 'gzip':
        decompress = zlib.createGunzip();
        break;
      case 'br':
        decompress = zlib.createBrotliDecompress();
        break;
      case 'deflate':
        decompress = zlib.createInflate();
        break;
      default:
        break;
    }

    if(decompress) {
      res.pipe(decompress);
      let buffer = Buffer.from('', 'utf8');

      decompress.on('data', (chunk) => (buffer = Buffer.concat([buffer, chunk])));

      decompress.on('end', async () => {
        let body = buffer.toString();
        if(body) {
          reply.removeHeader('content-length');
          body = call_back.call(this, body);
        }
        reply.compress(body);
      });
    } else reply.send(res);
  } else reply.send(res);
}

You will also need:

  await server.register(
    import('@fastify/compress'),
    { global: false }
  )

And call it using:

  onResponse: async (request, reply, res) => {
        change_body(request, reply, res, function(body) {
          return body.replace('Search This', 'Replace with');
        })
      },

advany avatar Aug 10 '22 13:08 advany

@mcollina would be great if this could be added to fastify like a hook or something. something like rewriteBody so please who need to change the body can easily do it

advany avatar Aug 10 '22 13:08 advany

Reopened as a feature request

I think we could provide a feature for it, but as your example shows, there are stuff like compression and content type to deal with.

I think a good tread off between simplicity and usability could be:

reply.from('/', {
  onPayload(bufferPayload, reply) {
     // manage the buffer payload
     reply.send({ whatever })
  }
})

I'm assuming users do not want deal with stream here

Eomm avatar Aug 10 '22 17:08 Eomm