Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

openapi3gen does not generate nullable: true for pointers #968

Closed
josephbuchma opened this issue Jun 17, 2024 · 2 comments · Fixed by #987
Closed

openapi3gen does not generate nullable: true for pointers #968

josephbuchma opened this issue Jun 17, 2024 · 2 comments · Fixed by #987

Comments

@josephbuchma
Copy link

This should include "nullable": true
https://github.com/getkin/kin-openapi/blob/master/openapi3gen/openapi3gen_test.go#L115-L117

This issue is not possible to fix using openapi3gen.SchemaCustomizer because reflect.Type passed into openapi3.SchemaCustomizerFn is never a pointer.

@endertunc
Copy link
Contributor

endertunc commented Jun 28, 2024

You can still work around it using SchemaCustomizer and custom StructTag.

type StructWithPointer struct {
	A *string `json:"a" nullable`
}
	
customizer := openapi3gen.SchemaCustomizer(func(name string, ft reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
	if _, ok := tag.Lookup("nullable"); ok {
		schema.Nullable = true
	}
	return nil
})

For the solution to the problem, this is where we lose the "pointer" information https://github.com/getkin/kin-openapi/blob/master/openapi3gen/openapi3gen.go#L204-L206

I think something like following should solve the problem:

isNullable := false
for t.Kind() == reflect.Ptr {
	t = t.Elem()
	isNullable = true
}

...

schema := &openapi3.Schema{} // this already exists
schema.Nullable = isNullable // new change

I did run the tests you pointed and it seems to work. I am not sure if there are edge cases for but I am happy to raise a PR if this is acceptable.

On the other hand, openapi3gen seems to be trying to be minimalisti. For example, you also don't get required in anyone your "required" fields. I think that's they idea with SchemaCustomizer which allow you to customize the schema the way you want so the workaround I mentioned might be the suggest way to solve these kind of issues :)

@fenollp
Copy link
Collaborator

fenollp commented Jun 28, 2024

@endertunc your patch proposal seems very reasonable. Please open a PR :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants