NorfairKing / autodocodec

self(auto)- documenting encoders and decoders
MIT License
121 stars 20 forks source link

Set default on property schema and not on the object level #19

Closed joel-bach closed 2 years ago

joel-bach commented 2 years ago

Currently, generating OpenAPI schemas with codecs such as optionalFieldWithDefault lead to an invalid OpenAPI spec as can be seen by supplying autodocodec-api-usage/test_resources/openapi-schema/example.json to https://validator.swagger.io (full link:

{"messages":["attribute components.schemas.Example.default is not of type `object`"]}

The reason is that the supplied default value does not match the schema of the object, which makes sense given the default value was supplied to a field of the object and not the object itself. This also leads to default values of different fields overwriting each other as there can only be one default value on the object level.

This PR aims to fix this bug by setting the default value on the property level. This leads to a valid OpenAPI spec as can be seen here (empty object means no validation errors):

{}
NorfairKing commented 2 years ago

Looks great and happy to merge as-is, but is there any way we could integrate this validation that you're using with the test suite?

joel-bach commented 2 years ago

I was looking for solutions to validate the OpenAPI spec as well, but I did not find anything promising in Haskell. One option I found is this article about a GitHub action, but that does not seem viable for all the specifications in this repo. Another, probably better route would be to use openapi-generator-cli. There is a nix package for that and I just found out that it has a validate command built-in (e. g. openapi-generator-cli validate -i somespec.json) and I remember that openapi-generator-cli failed to generate code because of the default value problem, so maybe this is good enough :thinking: