fox1t / fastify-multer

Fastify plugin for handling multipart/form-data
MIT License
89 stars 14 forks source link

Schema validation #2

Closed mkolbusz closed 4 years ago

mkolbusz commented 4 years ago

I would like to send a file along with the number field that is required. I would like to use the fastify schema validation so I write:

let schema = {
    description: 'Upload image',
    tags: ['images'],
    consumes: ['multipart/form-data'],
    summary: 'Upload image for the user',
    body: {
      type: 'object',
      required: ['id'],
      properties: {
        id: { type: 'integer'}
      }
    }
}

I have addes fastify.register(multer.contentParser); before the router registration and then have route registration like this one:

fastify.post('/images', { preHandler: upload.single('image'), schema: schema }, imagesController.store.bind(imagesController));

And when I send a form data with id and image I get error message from fastify:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "body should be object"
}

Is it possible to use build-in fastify schema validator while using multer?

fox1t commented 4 years ago

Unfortunately the schemas are only usable for json bodies. Here we are using a multipart body.

madx commented 4 years ago

I'm encountering this issue as well as I have a route that gets some files through fastify-multer but also some non-file POST data in the body that I would like to validate.

Do you have a recommended way of validating this data? Is there a way to make schemas usable for multipart bodies as well?

trey-m commented 3 years ago

I'm encountering this issue as well as I have a route that gets some files through fastify-multer but also some non-file POST data in the body that I would like to validate.

Do you have a recommended way of validating this data? Is there a way to make schemas usable for multipart bodies as well?

I am currently facing this obstacle as well. Unfortunately I think the best bet would be to do the manual validations yourself in the handler. Not among the best practices when it comes to fastify but in this case it may be the only way.

If you did find a better alternative please do post it!

taythebot commented 3 years ago

I found a workaround to this issue. Instead of executing multer in the preHandler hook, if you execute it in the preValidation hook your schema validation will run afterwards!

  // Register multipart handler
  fastify.register(multer.contentParser)

  // Create new post
  fastify.post(
    '/',
    {
      schema: newSchema,
      preValidation: multer({
        limits: {
          fields: 2,
          fileSize: 31457280,
          files: 1,
          parts: 3,
        },
      }).single('file'),
    },
    async (req, _) => {
      console.log(req.file) // file here
      console.log(req.body) // body here

      return 'ok'
    }
  )