Skip to content

BUG @Size is ignored in properties using collections when using oas 3.1.0 #4702

Closed
@Lorenzo-Bracci

Description

@Lorenzo-Bracci

Problem

When generating OpenAPI 3.1.0 spec the @Size annotation on property with a collection type is ignored. The expected behaviour is that the generated property has both maxItems and minItems set but these properties are not found in the generated open api.

Expected behaviour

@Size#min is used to generate minItems and @Size#max is used to generate maxItems for the generated property schema

Reproducer

The issues is reproduced in the following test:

    @Test(description = "Shows that @Size is not correctly handled in properties using collections when using oas 3.1.0")
    public void testModelUsingCollectionTypePropertyDoesNotHandleSizeAnnotationForOas31() {

        String expectedYaml = "DtoUsingSizeOnCollection:\n" +
                "  type: object\n" +
                "  properties:\n" +
                "    myField:\n" +
                "      maxItems: 100\n" +
                "      minItems: 1\n" +
                "      type: array\n" +
                "      items:\n" +
                "        type: string";

        Map<String, io.swagger.v3.oas.models.media.Schema> stringSchemaMap = ModelConverters.getInstance(true).readAll(DtoUsingSizeOnCollection.class);
        // fails as the maxItems/minItems will not be added to the schema of myField for oas 3.1.0
        SerializationMatchers.assertEqualsToYaml31(stringSchemaMap, expectedYaml);
    }

    public class DtoUsingSizeOnCollection {
        @Size(min = 1, max = 100)
        private List<String> myField;

        public List<String> getMyField() {
            return myField;
        }

        public void setMyField(List<String> myField) {
            this.myField = myField;
        }
    }

Investigation with proposed solution

Looking at the ModelResolver.applyBeanValidatorAnnotations code (which is where information from bean validation annotations are processed), there is a check that the property input parameter of type Schema is an instance of ArraySchema. If the check succeeds then the information from @Size is propagated to the generated schema (using the minItems/maxItems properties). Nevertheless for open api 3.1.0 property will be of type JsonSchema instead of ArraySchema and therefore the information from @Size will not be used. A possible solution would be that instead of using (property instanceof ArraySchema) a check is performed on the type/types fields of property to ensure that the property is an array schema.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions