How to generate nullable struct references? #78
-
Hello, I want to be able to make a struct nullable: type Bar struct {
Foo *FooStruct `json:"foo"`
} I’m using kin-openapi, to validate my http calls against my generated OpenAPI file, and for a struct to be optional in my http response, I need: ...
- foo:
- nullable: true
- allOf:
- $ref: '#components/schemas/foostruct'
... I was able to move the generated Would you have any suggestions ? Thanks a lot in advance ! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I think https://go.dev/play/p/Dt5HxQ8XJUp jr.DefaultOptions = append(jr.DefaultOptions, jsonschema.InterceptNullability(func(params jsonschema.InterceptNullabilityParams) {
if params.RefDef != nil && params.Type.Kind() == reflect.Ptr {
params.Schema.WithAllOf(jsonschema.Null.ToSchemaOrBool(), params.OrigSchema.ToSchemaOrBool())
params.Schema.Ref = nil
}
})) components:
schemas:
Bar:
properties:
foo:
allOf:
- nullable: true
- $ref: '#/components/schemas/FooStruct'
type: object
type: object or jr.DefaultOptions = append(jr.DefaultOptions, jsonschema.InterceptNullability(func(params jsonschema.InterceptNullabilityParams) {
if params.RefDef != nil && params.Type.Kind() == reflect.Ptr {
params.Schema.AddType(jsonschema.Null)
params.Schema.WithAllOf(params.OrigSchema.ToSchemaOrBool())
params.Schema.Ref = nil
}
})) components:
schemas:
Bar:
properties:
foo:
allOf:
- $ref: '#/components/schemas/FooStruct'
nullable: true
type: object
type: object
FooStruct: Alternatively, you can put nullability under the refrence, but this would also affect the cases when field is a value, not a pointer (might be undesirable). https://go.dev/play/p/_J09FYf8uRF jr.DefaultOptions = append(jr.DefaultOptions, jsonschema.InterceptNullability(func(params jsonschema.InterceptNullabilityParams) {
if params.Type.Kind() == reflect.Ptr {
params.Schema.AddType(jsonschema.Null)
}
})) components:
schemas:
Bar:
properties:
foo:
$ref: '#/components/schemas/FooStruct'
type: object
FooStruct:
nullable: true
properties:
baz:
type: string
type: object |
Beta Was this translation helpful? Give feedback.
I think
jsonschema.InterceptNullability
would be suitable for this, please check an example.https://go.dev/play/p/Dt5HxQ8XJUp
or