feat: implement interface for alternative JSONSchema() function - #130
feat: implement interface for alternative JSONSchema() function#130olistrik wants to merge 3 commits into
Conversation
…ernative-json-schema-interface
|
@samlown I've added tests for this one too! |
|
@olistrik love this change, switching to your fork for now :D In my case it was super beneficial to have this method, to avoid cumbersome tags for the enum values. Now, I can, relatively easily, manage enum values in code, and those are reflected in the schema. type ActionType string
const (
ActionTypeA string = "A"
ActionTypeB string = "B"
ActionTypeC string = "C"
)
func (t ActionType) JSONSchema(reflect func(any) *jsonschema.Schema) *jsonschema.Schema {
return &jsonschema.Schema{
Type: "string",
Enum: []any{
ActionTypeA,
ActionTypeB,
ActionTypeC,
},
}
} |
|
@8tomat8 glad you like it! Though unless you're using the |
|
@8tomat8 oh also, if you do need the reflect callback, I'd recommend using the klippa-app fork rather than my own. I don't plan on maintaining my fork, but klippa will continue to pull upstream changes and maintain their fork if these changes don't get merged here. |
Hi there,
I have a particular use case of jsonschema where we have the following situation:
We have a
Foo"enum" that has a limited set of known values, and implements various marshallers so that a string representation of the "enum" is used for all inbound and outbound serialization.Unfortunately we've noticed that when serializing a map with a key of
Foojsonschema only considers the underlying integer value when reflecting the schema and produces the following schema:{ "type": "object", "patternProperties" : { "^[0-9]+$": ... } }Given that the JSON marshaller will (un)marshal map keys using the TextMarshaller interface, this is an issue for us. Perhaps their is also an argument that jsonschema should do the same, but my first approach to this was to try and provide an alternative schema using
JSONSchemaandJSONSchemaExtend. However, I have noticed thatJSONSchemain particular is only usable for leaf nodes, you cannot return the result of a newjsonschema.Reflectas this may not have the same configuration as the parent and it will nest a new schema in the parent.JSONSchemaExtendis possible to use for this, however it requires significant modification to the resulting schema in a way that I'm not personally comfortable with.With this merge request I've added an alternative definition of the
JSONSchemainterface that provides areflectcallback which can be used to continue reflection into children.The implementation of this for the foo map would be as follows:
My reasoning about using the same function name
JSONSchemaoverJSONSchemaInterceptor something similar, is because it keeps backwards compatibility while preventing implementing both interfaces on a single type, which would be a strange thing to do imo.I haven't written tests for this yet, I wanted to hear your opinions on it first.