Skip to content

Commit

Permalink
Merge pull request #205 from feenst/update-validation-for-object
Browse files Browse the repository at this point in the history
Align schema validation with specification for objects
  • Loading branch information
philsturgeon committed May 13, 2022
2 parents 21352a8 + 485ebb4 commit 534bb3f
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 1 deletion.
8 changes: 8 additions & 0 deletions lib/validators/spec.js
Expand Up @@ -330,6 +330,14 @@ function validateRequiredPropertiesExist (schema, schemaId) {
}
}

// The "required" keyword is only applicable for objects
if (Array.isArray(schema.type) && !schema.type.includes("object")) {
return;
}
else if (!Array.isArray(schema.type) && schema.type !== "object") {
return;
}

if (schema.required && Array.isArray(schema.required)) {
let props = {};
collectProperties(schema, props);
Expand Down
@@ -0,0 +1,86 @@
swagger: "2.0"
info:
title: API documentation
version: "1.0.0"
paths:
/product:
get:
responses:
"200":
schema:
$ref: "#/definitions/product"
description: Successful
/products:
get:
responses:
"200":
schema:
$ref: "#/definitions/products"
description: Successful
/mood:
get:
responses:
"200":
schema:
$ref: "#/definitions/mood"
description: Successful
/temperature:
get:
responses:
"200":
schema:
$ref: "#/definitions/temperature"
description: Successful
/age:
get:
responses:
"200":
schema:
$ref: "#/definitions/age"
description: Successful
/hunger:
get:
responses:
"200":
schema:
$ref: "#/definitions/hunger"
description: Successful
definitions:
product:
type: object
properties:
expiration:
type: string
format: date
name:
type: string
weight:
type: number
required:
- name
products:
type: array
items:
$ref: "#/definitions/product"
required:
- items # <--- Should not be validated since type is not object
mood:
type: string
example: nostalgic
required:
- length # <--- Should not be validated since type is not object
temperature:
type: number
example: 86
required:
- precision # <--- Should not be validated since type is not object
age:
type: integer
example: 42
required:
- factors # <--- Should not be validated since type is not object
hunger:
type: boolean
example: true
required:
- truth # <--- Should not be validated since type is not object
7 changes: 6 additions & 1 deletion test/specs/validate-spec/validate-spec.spec.js
Expand Up @@ -140,7 +140,12 @@ describe("Invalid APIs (Swagger 2.0 specification validation)", () => {
valid: false,
file: "array-response-body-no-items.yaml",
error: 'Validation failed. /paths/users/get/responses/200/schema is an array, so it must include an \"items\" schema'
}
},
{
name: "only validate required properties on objects",
valid: true,
file: "only-validate-required-properties-on-objects.yaml"
},
];

it('should pass validation if "options.validate.spec" is false', async () => {
Expand Down

0 comments on commit 534bb3f

Please sign in to comment.