swagger-core icon indicating copy to clipboard operation
swagger-core copied to clipboard

@Schema implementation and type are ignored when annotated at model-level

Open arteymix opened this issue 4 years ago • 1 comments

I'm trying to add @Schema definitions on my path and query parameter models, but the type and implementation attributes are ignored and object is inferred instead.

For example:

@Schema(implementation=String.class, example = "123-456")
public class ModelIdArg {

    public String a;

    public static ModelIdArg valueOf(String s) {
        // convert s into SomeModel...
    }
}

That will result in a {"type": "object", "properties": {"a": {"type": "string"}, "example": "123-456"} definition when used as follow:

@GET
public Model findById(ModelIdArg arg) { ... }

Whereas defining @Schema directly on the method will result in the expected {"type": "string", "example": "123-456"}:

@GET
public Model findById(@Schema(implementation=String.class) ModelIdArg arg) { ... }

Is there something I'm missing? Why does example get picked up? but not implementation nor type?

arteymix avatar Jul 22 '21 17:07 arteymix

I managed to resolve this by using a custom ModelConverter that retrieves the original AnnotatedType instead of using the one inferred from the parameter:

public class ArgModelConverter extends ModelResolver {

    public ArgModelConverter( ObjectMapper mapper ) {
        super( mapper );
    }

    @Override
    public Schema resolve( AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain ) {
        JavaType t = Json.mapper().constructType( type.getType() );
        if ( Arg.class.isAssignableFrom( t.getRawClass() ) ) {
            // I'm suspecting there's a bug in Swagger that causes request parameters annotations to shadow the
            // definitions in the class's Schema annotation
            return super.resolve( new AnnotatedType( ( t.getRawClass() ) ), context, chain );
        }
        if ( chain.hasNext() ) {
            return chain.next().resolve( type, context, chain );
        } else {
            return null;
        }
    }
}

arteymix avatar Feb 22 '22 22:02 arteymix