Gi60s / openapi-enforcer

Apache License 2.0
94 stars 22 forks source link

Enable exceptions for deserialization of string formats #119

Closed darren-reddick closed 3 years ago

darren-reddick commented 3 years ago

Hi, We encountered an issue recently where we are validating the json response body from an API against an OpenAPI schema which has some fields of type string and format date. The API passes through a value from a backend system of 0000-00-00 which represents an empty date value. This causes an error during deserialization as it cannot be converted to a javascript Date object.

We have worked around this by overriding the deserialize function for string dates to return the epoch date Date(0) when it encounters string 0000-00-00. A nice feature would be to provide a string array of valid exceptions for each of the string format types which return some default object when deserialized.

I understand that custom string format types are supported but it felt unnecessary to use these and maintain mostly the same code as the builtin date format.

Does this sound like it could be a useful feature?

Gi60s commented 3 years ago

I can see the need to have something like this, although I have a different proposal. We could add the ability to create data type hooks. Hooks allow you to run additional processing before or after something occurs.

It might be used somehow like this:

Schema.hook('beforeDeserialize', (value, schema, exception) => {
    if (schema.type === 'string' && schema.format === 'date' && value === '0000-00-00') {
        return {
            value: new Date(0),
            done: true // if done then don't allow any other deserialize functions to run, we are done
        }
    } else {
        // we didn't make any changes so pass along the unchanged value and let other deserializers work on it
        return {
            value,
            done: false
        }
    }
})
darren-reddick commented 3 years ago

Nice! I totally agree that keeping this logic separate from the deserialization is much nicer and would enable solving some more complex scenarios.

Gi60s commented 3 years ago

This functionality has been implemented in version 1.15.0. It has been published to NPM and is documented here: https://byu-oit.github.io/openapi-enforcer/api/components/schema#hook. I hope you don't mind but I even used your example in the docs.

darren-reddick commented 3 years ago

Thanks v. much for this it looks like a great addition.