wpz
wpz

Reputation: 3

Multer and Joi compatibility

I am trying to do uploading of files in expressJS using multer. I am using postman and set the header to multipart/form-data I need to validate the request body first using Joi but when I tried to place the Joi validation middleware first, it doesn't work. And when I placed the multer middleware first, the upload worked even if the request body didn't pass the validations of the Joi middleware. How can I fix this?

Upvotes: 0

Views: 3872

Answers (1)

craynccc
craynccc

Reputation: 56

I had a similar problem and after some search and try and error, this solved it to me. The thing to keep in mind is to put the Joi validator after multer upload and change the validation scheme a bit.

I've condensed the code into one file to make it a little clearer, so it's missing its dependencies, I hope you get the idea:

const createFile = {
  body: {
    name: Joi.string().required(),
    description: Joi.string(),
    protected: Joi.boolean().required()
  },
  file: Joi.string().required()
};

router
  .route('/files')
  .post(upload.single('file'), validate(createFile), (req, res, next) => {
      //controller logic
    }
  );

/**
 * @swagger
 * path:
 *  /files:
 *    post:
 *      summary: Upload a file and its metadata to the server.
 *      description: Create a file.
 *      consumes:
 *        - multipart/form-data
 *      tags: [Files]
 *      security:
 *        - bearerAuth: []
 *      requestBody:
 *        required: true
 *        content:
 *          multipart/form-data:
 *            schema:
 *              type: object
 *              required:
 *                - name
 *                - protected
 *                - file
 *              properties:
 *                name:
 *                  type: string
 *                description:
 *                  type: string
 *                protected:
 *                  type: boolean
 *                  default: false
 *                file:
 *                  type: string
 *                  format: binary
 *      responses:
 *        "201":
 *          description: Created
 *          content:
 *            application/json:
 *              schema:
 *                type: object
 *                properties:
 *                  success:
 *                    type: boolean
 *                  message:
 *                    type: string
 *                  data:
 *                    type: object
 *                    $ref: '#/components/schemas/File'
 *        "401":
 *          $ref: '#/components/responses/Unauthorized'
 *        "403":
 *          $ref: '#/components/responses/Forbidden'
 */

Upvotes: 3

Related Questions