Add "struct_references" configuration (#155)

Adds a "struct_references" configuration that will:

* Use a pointer type for struct fields that are a complex type
* The behaviour can be overridden by setting "pointer: false" in the
  proceeding comment blocks
* Sets the "omitempty: true" flag on fields matching the criteria.
  This can also be overriden by setting "omitempty: false"

Although we'd debated not setting the pointer for array elements, it did turn out to be simpler to set them everywhere and also made the documentation cleaner to have a single rule to explain.

Fixes #149.
This commit is contained in:
Nathan Stitt
2021-11-12 19:53:19 -08:00
committed by GitHub
parent 5401a62dcb
commit 2fdbb629be
5 changed files with 92 additions and 1 deletions
+17 -1
View File
@@ -244,7 +244,15 @@ func (g *generator) convertType(
goTyp, err := g.convertDefinition(
namePrefix, def, typ.Position, selectionSet, options, queryOptions)
if options.GetPointer() {
if g.getStructReference(def) {
if options.Pointer == nil || *options.Pointer {
goTyp = &goPointerType{goTyp}
}
if options.Omitempty == nil || *options.Omitempty {
oe := true
options.Omitempty = &oe
}
} else if options.GetPointer() {
// Whatever we get, wrap it in a pointer. (Because of the way the
// options work, recursing here isn't as connvenient.)
// Note this does []*T or [][]*T, not e.g. *[][]T. See #16.
@@ -253,6 +261,14 @@ func (g *generator) convertType(
return goTyp, err
}
// getStructReference decides if a field should be of pointer type and have the omitempty flag set.
func (g *generator) getStructReference(
def *ast.Definition,
) bool {
return g.Config.StructReferences &&
(def.Kind == ast.Object || def.Kind == ast.InputObject)
}
// convertDefinition decides the Go type we will generate corresponding to a
// particular GraphQL named type.
//