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

feat: Parse JSON fields when content-type is set. Fixes #278. #288

Merged
merged 4 commits into from Nov 1, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
60 changes: 60 additions & 0 deletions README.md
Expand Up @@ -340,6 +340,66 @@ hello: {
}
```

#### JSON non-file fields

If a non file field sent has `Content-Type` header starting with `application/json`, it will be parsed using `JSON.parse`.

The schema to validate JSON fields should look like this:

```js
hello: {
ShogunPanda marked this conversation as resolved.
Show resolved Hide resolved
properties: {
value: {
type: 'object',
properties: {
/* ... */
}
}
}
}
```

If you also use the shared JSON schema as shown above, this is a full example which validates the entire field:

```js
const opts = {
attachFieldsToBody: true,
sharedSchemaId: '#mySharedSchema'
}
fastify.register(require('fastify-multipart'), opts)

fastify.post('/upload/files', {
schema: {
body: {
type: 'object',
required: ['field'],
properties: {
field: {
allOf: [
{ $ref: '#mySharedSchema' },
{
properties: {
value: {
type: 'object'
properties: {
child: {
type: 'string'
}
}
}
}
}
]
}
}
}
}
}, function (req, reply) {
console.log({ body: req.body })
reply.send('done')
})
```

## Access all errors

We export all custom errors via a server decorator `fastify.multipartErrors`. This is useful if you want to react to specific errors. They are derived from [fastify-error](https://github.com/fastify/fastify-error) and include the correct `statusCode` property.
Expand Down
25 changes: 24 additions & 1 deletion index.js
Expand Up @@ -14,6 +14,7 @@ const sendToWormhole = require('stream-wormhole')
const deepmerge = require('deepmerge')
const { PassThrough, pipeline } = require('stream')
const pump = util.promisify(pipeline)
const secureJSON = require('secure-json-parse')

const kMultipart = Symbol('multipart')
const kMultipartHandler = Symbol('multipartHandler')
Expand Down Expand Up @@ -160,6 +161,7 @@ function fastifyMultipart (fastify, options, done) {
const RequestFileTooLargeError = createError('FST_REQ_FILE_TOO_LARGE', 'request file too large, please check multipart config', 413)
const PrototypeViolationError = createError('FST_PROTO_VIOLATION', 'prototype property is not allowed as field name', 400)
const InvalidMultipartContentTypeError = createError('FST_INVALID_MULTIPART_CONTENT_TYPE', 'the request is not multipart', 406)
const InvalidJSONFieldError = createError('FST_INVALID_JSON_FIELD_ERROR', 'a request field is not a valid JSON as declared by its Content-Type', 406)

fastify.decorate('multipartErrors', {
PartsLimitError,
Expand Down Expand Up @@ -353,15 +355,36 @@ function fastifyMultipart (fastify, options, done) {

request.pipe(bb)

function onField (name, fieldValue, fieldnameTruncated, valueTruncated) {
function onField (name, fieldValue, fieldnameTruncated, valueTruncated, encoding, contentType) {
let mimetype

// don't overwrite prototypes
if (getDescriptor(Object.prototype, name)) {
onError(new PrototypeViolationError())
return
}

// If it is a JSON field, parse it
if (contentType.startsWith('application/json')) {
// If the value was truncated, it can never be a valid JSON. Don't even try to parse
if (valueTruncated) {
onError(new InvalidJSONFieldError())
return
}

try {
fieldValue = secureJSON.parse(fieldValue)
mimetype = 'application/json'
} catch (e) {
onError(new InvalidJSONFieldError())
return
}
}

const value = {
fieldname: name,
mimetype,
encoding,
value: fieldValue,
fieldnameTruncated,
valueTruncated,
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -11,6 +11,7 @@
"fastify-error": "^0.3.0",
"fastify-plugin": "^3.0.0",
"hexoid": "^1.0.0",
"secure-json-parse": "^2.4.0",
"stream-wormhole": "^1.1.0"
},
"devDependencies": {
Expand Down