From 78bfe87dbffefbfb25d13fb705354ac03bbc52a1 Mon Sep 17 00:00:00 2001 From: Philipp Katz Date: Fri, 23 Jun 2023 16:28:24 +0200 Subject: [PATCH] fix: Empty body handling when attachFieldsToBody is keyValues --- index.js | 28 +++++++++++---------- test/multipart-empty-body.test.js | 42 +++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/index.js b/index.js index 7f0eafad..6dddb168 100644 --- a/index.js +++ b/index.js @@ -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 diff --git a/test/multipart-empty-body.test.js b/test/multipart-empty-body.test.js index 891a1aca..cc818d7c 100644 --- a/test/multipart-empty-body.test.js +++ b/test/multipart-empty-body.test.js @@ -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') +})