Skip to content

2021.5

Choose a tag to compare

@hauner hauner released this 23 Dec 09:57
· 2131 commits to main since this release

copied from openapi-processor-core

openapi-processor/openapi-processor-core#68, improved response type handling

this is a breaking change because it changes the code that gets generated by default. To keep the old behavior set result-style in the mapping.yaml to all. See the example below.

old behavior

currently if an endpoint returns multiple types, a success response (typically 200 ok) and at least one error response, the processor generates endpoint methods with an Object return value (or if generic something like ResponseType<?>) to handle the (usually) type wise unrelated ok and error responses.

For example, the following endpoint:

paths:
  /foo:
    get:
      responses:
        '200':
          description: json or plain text result
          content:
            application/json:
                schema:
                  $ref: '#/components/schemas/Foo'
            text/plain:
                schema:
                  type: string
        default:
          description: error
          content:
            application/xml:
                schema:
                  $ref: '#/components/schemas/Error'

will produce this java interface:

public interface Api {

    @Mapping("/foo")
    Object getFooApplicationJson();

    @Mapping("/foo")
    Object getFooTextPlain();

}

It generates a method for each success response with an Object response because the error and the success response (usually) do not have the same type as the error response.

Object is not a very useful result type because the compiler can't check if whatever we return in the implementation matches the openapi response type.

new behavior

Since it is common practice to handle errors by throwing exceptions (e.g. in combination with the Spring @ResponseStatus to provide the http response code) the endpoint methods don't need to return different types and it is possible to simply use the type of the success response.

With this release the processor will, by default, generate the endpoint methods with specific return types:

public interface Api {

    @Mapping("/foo")
    Foo getFooApplicationJson();

    @Mapping("/foo")
    String getFooTextPlain();

}

configuration

To switch between old and new behavior there is a new mapping configuration to control the style of the return type named result-style. It has two possible values: success or all. This is currently a global switch.

The default is success, i.e. the processor will automatically generate the code using the new behavior. In case the old behavior is required set the result-style to all.

openapi-processor-mapping: v2

options:
  package-name: ...

map:
  #result-style: success  # use the success result type, this is the default
  result-style: all # use an Object return type