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: Empty body handling when attachFieldsToBody is keyValues #450

Merged
merged 1 commit into from
Jul 17, 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
28 changes: 15 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,19 +165,21 @@ function fastifyMultipart (fastify, options, done) {
}
if (options.attachFieldsToBody === 'keyValues') {
const body = {}
for (const key of Object.keys(req.body)) {
const field = req.body[key]
if (field.value !== undefined) {
body[key] = field.value
} else if (Array.isArray(field)) {
body[key] = field.map(item => {
if (item._buf !== undefined) {
return item._buf.toString()
}
return item.value
})
} else if (field._buf !== undefined) {
body[key] = field._buf.toString()
if (req.body) {
for (const key of Object.keys(req.body)) {
const field = req.body[key]
if (field.value !== undefined) {
body[key] = field.value
} else if (Array.isArray(field)) {
body[key] = field.map(item => {
if (item._buf !== undefined) {
return item._buf.toString()
}
return item.value
})
} else if (field._buf !== undefined) {
body[key] = field._buf.toString()
}
}
}
req.body = body
Expand Down
42 changes: 42 additions & 0 deletions test/multipart-empty-body.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,45 @@ test('should not break with a empty request body when attachFieldsToBody is true
await once(res, 'end')
t.pass('res ended successfully')
})

test('should not break with a empty request body when attachFieldsToBody is keyValues', async function (t) {
t.plan(5)

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

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

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

const files = await req.saveRequestFiles()

t.ok(Array.isArray(files))
t.equal(files.length, 0)

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.pipe(req)

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