diff --git a/package-lock.json b/package-lock.json index 68c5adb7..61ab4e5c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "express-openapi-validator", - "version": "2.2.0", + "version": "2.3.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 2e5c9113..caf5883c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "express-openapi-validator", - "version": "2.2.0", + "version": "2.3.0", "description": "Automatically validate API requests using an OpenAPI 3 and Express.", "main": "dist/index.js", "scripts": { diff --git a/src/middlewares/util.ts b/src/middlewares/util.ts index d593ac05..9d0b4bb7 100644 --- a/src/middlewares/util.ts +++ b/src/middlewares/util.ts @@ -39,8 +39,13 @@ export function ajvErrorsToValidatorError(status, errors) { e.params && e.params.missingProperty && e.dataPath + '.' + e.params.missingProperty; + const additionalProperty = + e.params && + e.params.additionalProperty && + e.dataPath + '.' + e.params.additionalProperty; + const path = required || additionalProperty || e.dataPath || e.schemaPath; return { - path: required || e.dataPath || e.schemaPath, + path, message: e.message, errorCode: `${e.keyword}.openapi.validation`, }; diff --git a/test/request.bodies.ref.spec.ts b/test/request.bodies.ref.spec.ts index c720d6c1..a26e8bd3 100644 --- a/test/request.bodies.ref.spec.ts +++ b/test/request.bodies.ref.spec.ts @@ -50,4 +50,28 @@ describe(packageJson.name, () => { testProperty: 'abc', }) .expect(200)); + + it('should return 400 if an additional property is encountered', async () => + request(app) + .post(`${basePath}/request_bodies_ref`) + .send({ + testProperty: 'abc', + invalidProperty: 'abc', + invalidProperty2: 'abc', + }) + .expect(400) + .then(r => { + const errors = r.body.errors; + expect(errors) + .to.be.an('array') + .with.length(2); + expect(errors[0].path).to.equal('.body.invalidProperty'); + expect(errors[0].message).to.equal( + 'should NOT have additional properties', + ); + expect(errors[1].path).to.equal('.body.invalidProperty2'); + expect(errors[1].message).to.equal( + 'should NOT have additional properties', + ); + })); }); diff --git a/test/resources/request.bodies.ref.yaml b/test/resources/request.bodies.ref.yaml index 75c66158..b8f6bdcf 100644 --- a/test/resources/request.bodies.ref.yaml +++ b/test/resources/request.bodies.ref.yaml @@ -26,6 +26,7 @@ components: application/json: schema: type: object + additionalProperties: false properties: testProperty: type: string