fastify / fastify-multipart

Multipart support for Fastify
MIT License
490 stars 103 forks source link

Support firebase #548

Open ThomasKientz opened 1 month ago

ThomasKientz commented 1 month ago

Currently we can't use this plugin with serverless GCP (or Firebase).

As explained here https://github.com/fastify/fastify/issues/946#issuecomment-766319521 and in the doc for firebase, we need to use req.rawBody in order to parse files from multipart.

Uzlopak commented 1 month ago

the tests are not happy

ThomasKientz commented 1 month ago

the tests are not happy

@Uzlopak don't really understand why it's failing, looks good but return exit code 1

Uzlopak commented 1 month ago

The test coverage is Not 100%

Uzlopak commented 1 month ago

Well the problem is, that gcf is a glorified express router. So they preparse the body so that you dont have to. You get the body stream in rawBody. So maybe we need, like you suggest, a plugin which basically removes the default content type parsers and just assigns rawbody to body?!

climba03003 commented 1 month ago

What's comes my mind is something like?

function gcp(fastify) {
  // add pass through content-type parser
  fastify.addContentTypeParser('application/json', {}, (req, body, done) => {
    done(null, body.body);
  });

  // add stream transform for multipart when neccessary
  if (fastify.hasContentTypeParser('multipart/form-data')) {
    fastify.addHook('preParsing', function(request, reply, payload, done) {
      if(request.headers['content-type'].startsWith('multipart/form-data')) {
        // we override the `.pipe` method and return rawBody as new payload
        const pipe = request.raw.pipe
        request.raw.pipe = function(stream) {
          Readable.from([rawBody]).pipe(stream)
        }
        request.raw.originalPipe = pipe
        done(null, payload.rawBody)
      } else {
        done(null, payload)
      }
    })
  }
}
ThomasKientz commented 1 month ago

Should I pursue the current implementation of this pull request and add test coverage? @Uzlopak