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

Option to attach to body as key-value pairs #348

Merged
merged 7 commits into from
Jun 8, 2022
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export interface FastifyMultipartAttactFieldsToBodyOptions extends FastifyMultip
/**
* Only valid in the promise api. Append the multipart parameters to the body object.
*/
attachFieldsToBody: true
attachFieldsToBody: true | 'keyValues';

/**
* Manage the file stream like you need
Expand Down
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ function fastifyMultipart (fastify, options, done) {
})
}

if (options.attachFieldsToBody === true) {
if (options.attachFieldsToBody === true || options.attachFieldsToBody === 'keyValues') {
if (typeof options.sharedSchemaId === 'string') {
fastify.addSchema({
$id: options.sharedSchemaId,
Expand All @@ -147,6 +147,18 @@ 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 (field._buf !== undefined) {
body[key] = field._buf.toString()
zone117x marked this conversation as resolved.
Show resolved Hide resolved
}
}
req.body = body
}
})
}

Expand Down
100 changes: 100 additions & 0 deletions test/multipart-attach-body.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const http = require('http')
const path = require('path')
const fs = require('fs')
const { once } = require('events')
const { Readable } = require('stream')

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

Expand Down Expand Up @@ -59,6 +60,105 @@ test('should be able to attach all parsed fields and files and make it accessibl
t.pass('res ended successfully')
})

test('should be able to attach all parsed field values and files and make it accessible through "req.body"', async function (t) {
t.plan(6)

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

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

const original = fs.readFileSync(filePath, 'utf8')

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

t.same(Object.keys(req.body), ['upload', 'hello'])

t.equal(req.body.upload, original)
t.equal(req.body.hello, 'world')

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', fs.createReadStream(filePath))
form.append('hello', 'world')
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')
})

test('should be able to attach all parsed field values and files with custom "onFile" handler and make it accessible through "req.body"', async function (t) {
t.plan(7)

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

async function onFile (part) {
t.pass('custom onFile handler')
const buff = await part.toBuffer()
const decoded = Buffer.from(buff.toString(), 'base64').toString()
part.value = decoded
}

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

const original = 'test upload content'

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

t.same(Object.keys(req.body), ['upload', 'hello'])

t.equal(req.body.upload, original)
t.equal(req.body.hello, 'world')

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.append('hello', 'world')
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')
})

test('should be able to define a custom "onFile" handler', async function (t) {
t.plan(7)

Expand Down