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

Remove legacy addToBody and callback API #465

Merged
merged 7 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
161 changes: 2 additions & 159 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const Busboy = require('@fastify/busboy')
const os = require('os')
const fp = require('fastify-plugin')
const eos = require('end-of-stream')
const { createWriteStream } = require('fs')
const { unlink } = require('fs').promises
const path = require('path')
Expand Down Expand Up @@ -35,68 +34,6 @@ function setMultipart (req, payload, done) {
done()
}

function attachToBody (options, req, reply, next) {
if (req.raw[kMultipart] !== true) {
next()
return
}

const consumerStream = options.onFile || defaultConsumer
const body = {}
const mp = req.multipart((field, file, filename, encoding, mimetype) => {
body[field] = body[field] || []
body[field].push({
data: [],
filename,
encoding,
mimetype,
limit: false
})

const result = consumerStream(field, file, filename, encoding, mimetype, body)
if (result && typeof result.then === 'function') {
result.catch((err) => {
// continue with the workflow
err.statusCode = 500
file.destroy(err)
})
}
}, function (err) {
if (!err) {
req.body = body
}
next(err)
}, options)

mp.on('field', (key, value) => {
if (key === '__proto__' || key === 'constructor') {
mp.destroy(new Error(`${key} is not allowed as field name`))
return
}
if (body[key] === undefined) {
body[key] = value
} else if (Array.isArray(body[key])) {
body[key].push(value)
} else {
body[key] = [body[key], value]
}
})
}

function defaultConsumer (field, file, filename, encoding, mimetype, body) {
const fileData = []
const lastFile = body[field][body[field].length - 1]
file.on('data', data => { if (!lastFile.limit) { fileData.push(data) } })
file.on('limit', () => { lastFile.limit = true })
file.on('end', () => {
if (!lastFile.limit) {
lastFile.data = Buffer.concat(fileData)
} else {
lastFile.data = undefined
}
})
}

function busboy (options) {
try {
return new Busboy(options)
Expand All @@ -117,26 +54,8 @@ function fastifyMultipart (fastify, options, done) {
}

const attachFieldsToBody = options.attachFieldsToBody
if (options.addToBody === true) {
if (typeof options.sharedSchemaId === 'string') {
fastify.addSchema({
$id: options.sharedSchemaId,
type: 'object',
properties: {
encoding: { type: 'string' },
filename: { type: 'string' },
limit: { type: 'boolean' },
mimetype: { type: 'string' }
}
})
}

fastify.addHook('preValidation', function (req, reply, next) {
attachToBody(options, req, reply, next)
})
}

if (options.attachFieldsToBody === true || options.attachFieldsToBody === 'keyValues') {
if (attachFieldsToBody === true || attachFieldsToBody === 'keyValues') {
if (typeof options.sharedSchemaId === 'string') {
fastify.addSchema({
$id: options.sharedSchemaId,
Expand All @@ -163,7 +82,7 @@ function fastifyMultipart (fastify, options, done) {
}
}
}
if (options.attachFieldsToBody === 'keyValues') {
if (attachFieldsToBody === 'keyValues') {
const body = {}
if (req.body) {
for (const key of Object.keys(req.body)) {
Expand Down Expand Up @@ -210,9 +129,6 @@ function fastifyMultipart (fastify, options, done) {
fastify.decorateRequest('tmpUploads', null)
fastify.decorateRequest('savedRequestFiles', null)

// legacy
fastify.decorateRequest('multipart', handleLegacyMultipartApi)

// Stream mode
fastify.decorateRequest('file', getMultipartFile)
fastify.decorateRequest('files', getMultipartFiles)
Expand All @@ -229,79 +145,6 @@ function fastifyMultipart (fastify, options, done) {
return this.raw[kMultipart] || false
}

// handler definition is in multipart-readstream
// handler(field, file, filename, encoding, mimetype)
// opts is a per-request override for the options object
function handleLegacyMultipartApi (handler, done, opts) {
if (typeof handler !== 'function') {
throw new Error('handler must be a function')
}

if (typeof done !== 'function') {
throw new Error('the callback must be a function')
}

if (!this.isMultipart()) {
done(new Error('the request is not multipart'))
return
}

const log = this.log

log.warn('the multipart callback-based api is deprecated in favour of the new promise api')
log.debug('starting multipart parsing')

const req = this.raw

const busboyOptions = deepmergeAll({ headers: req.headers }, options || {}, opts || {})
const stream = busboy(busboyOptions)
let completed = false
let files = 0

req.on('error', function (err) {
stream.destroy()
if (!completed) {
completed = true
done(err)
}
})

stream.on('finish', function () {
log.debug('finished receiving stream, total %d files', files)
if (!completed) {
completed = true
setImmediate(done)
}
})

stream.on('file', wrap)

req.pipe(stream)
.on('error', function (error) {
req.emit('error', error)
})

function wrap (field, file, filename, encoding, mimetype) {
log.debug({ field, filename, encoding, mimetype }, 'parsing part')
files++
eos(file, waitForFiles)
if (field === '__proto__' || field === 'constructor') {
file.destroy(new Error(`${field} is not allowed as field name`))
return
}
handler(field, file, filename, encoding, mimetype)
}

function waitForFiles (err) {
if (err) {
completed = true
done(err)
}
}

return stream
}

function handleMultipart (opts = {}) {
if (!this.isMultipart()) {
throw new InvalidMultipartContentTypeError()
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"@fastify/error": "^3.0.0",
"@fastify/swagger": "^8.3.1",
"@fastify/swagger-ui": "^1.8.0",
"end-of-stream": "^1.4.4",
"fastify-plugin": "^4.0.0",
"secure-json-parse": "^2.4.0",
"stream-wormhole": "^1.1.0"
Expand Down
Loading