Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix file stream consumption when buffer has not loaded yet #461

Merged
merged 2 commits into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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')
})