PayU / openapi-validator-middleware

Input validation using Swagger (Open API) and ajv
Apache License 2.0
144 stars 50 forks source link

Express multer with openapi 3 #106

Closed mmacai closed 4 years ago

mmacai commented 4 years ago

Hi, I want to use openapi/swagger version 3 and I have couple of endpoints using multipart/form-data.

Not sure if this is a bug or I'm doing something wrong.

My setup:

const inputValidationOptions = {
    expectFormFieldsInBody: true
};
swaggerValidator.init('src/openapi/api.schema.yml', inputValidationOptions);

const multerMiddleware = multer({ ... });

router.put(
  '/:id',
  multerMiddleware.single('photo'),
  swaggerValidator.validate,
  async (req: Request, res: Response) => {
    // ...
  }
);

Swagger:

requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          photo:
            type: string
            format: binary

Getting this error:

TypeError: validator.validate is not a function

Checked the source code and in src/middleware.js -> _validateBody is this const validator = methodSchema.body[contentType] || methodSchema.body;. So it's using content-type header to get the validator. In my case the value is multipart/form-data; boundary=--------------------------517000622299074484111234, but it's expecting only multipart/form-data. Thus it can't access the validator.

Did I miss something or it's issue in middleware?

kibertoad commented 4 years ago

@mmacai Yeah, this is an edge-case that is not handled correctly now.

Take a look at this PR: https://github.com/Zooz/api-schema-builder/pull/29/files (api-schema-builder is a dependency for express-ajv-swagger-validation) Probably we need same thing for request validation as well. If you can submit a PR with test for this, I would be more than happy to review.

mmacai commented 4 years ago

@kibertoad sure, I'll put something together.

mmacai commented 4 years ago

@kibertoad The change should be in this library or api-schema-builder? Going through api-schema-builder codebase and I'm a bit lost.