Skip to content

Commit

Permalink
Fix file stream consumption when buffer has not loaded yet (#461)
Browse files Browse the repository at this point in the history
* change condition to check for undefined and null values on internal buffer

* add test
  • Loading branch information
andersonjoseph authored Jul 21, 2023
1 parent 5481545 commit 8096bc5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,12 @@ function fastifyMultipart (fastify, options, done) {
body[key] = field.value
} else if (Array.isArray(field)) {
body[key] = field.map(item => {
if (item._buf !== undefined) {
if (item._buf) {
return item._buf.toString()
}
return item.value
})
} else if (field._buf !== undefined) {
} else if (field._buf) {
body[key] = field._buf.toString()
}
}
Expand Down
47 changes: 47 additions & 0 deletions test/multipart-attach-body.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const path = require('path')
const fs = require('fs')
const { once } = require('events')
const { Readable } = require('stream')
const pump = require('pump')
const { writableNoopStream } = require('noop-stream')

const filePath = path.join(__dirname, '../README.md')

Expand Down Expand Up @@ -387,3 +389,48 @@ test('should be able to attach all parsed field values and files with custom "on
await once(res, 'end')
t.pass('res ended successfully')
})

test('should handle file stream consumption when internal buffer is not yet loaded', async function (t) {
t.plan(3)

const fastify = Fastify()
t.teardown(fastify.close.bind(fastify))

async function onFile (part) {
pump(part.file, writableNoopStream()).once('end', () => {
t.pass('stream consumed successfully')
})
}

fastify.register(multipart, { attachFieldsToBody: 'keyValues', onFile })

const original = 'test upload content'

fastify.post('/', async function (req, reply) {
t.ok(req.isMultipart())
reply.code(200).send()
})

await fastify.listen({ port: 0 })

// request
const form = new FormData()
const opts = {
protocol: 'http:',
hostname: 'localhost',
port: fastify.server.address().port,
path: '/',
headers: form.getHeaders(),
method: 'POST'
}

const req = http.request(opts)
form.append('upload', Readable.from(Buffer.from(original).toString('base64')))
form.pipe(req)

const [res] = await once(req, 'response')
t.equal(res.statusCode, 200)
res.resume()
await once(res, 'end')
t.pass('res ended successfully')
})

0 comments on commit 8096bc5

Please sign in to comment.