git.sr.ht/~sircmpwn/gqlgen@v0.0.0-20200522192042-c84d29a1c940/docs/content/recipes/modelgen-hook.md (about)

     1  ---
     2  title: "Allowing mutation of generated models before rendering"
     3  description: How to use a model mutation function to insert a ORM-specific tags onto struct fields.
     4  linkTitle: "Modelgen hook"
     5  menu: { main: { parent: 'recipes' } }
     6  ---
     7  
     8  The following recipe shows how to use a `modelgen` plugin hook to mutate generated
     9  models before they are rendered into a resulting file. This feature has many uses but
    10  the example focuses only on inserting ORM-specific tags into generated struct fields. This
    11  is a common use case since it allows for better field matching of DB queries and
    12  the generated data structure.
    13  
    14  First of all, we need to create a function that will mutate the generated model.
    15  Then we can attach the function to the plugin and use it like any other plugin.
    16  
    17  ``` go
    18  import (
    19  	"fmt"
    20  	"os"
    21  
    22  	"git.sr.ht/~sircmpwn/gqlgen/api"
    23  	"git.sr.ht/~sircmpwn/gqlgen/codegen/config"
    24  	"git.sr.ht/~sircmpwn/gqlgen/plugin/modelgen"
    25  )
    26  
    27  // Defining mutation function
    28  func mutateHook(b *modelgen.ModelBuild) *modelgen.ModelBuild {
    29  	for _, model := range b.Models {
    30  		for _, field := range model.Fields {
    31  			field.Tag += ` orm_binding:"` + model.Name + `.` +  field.Name + `"`
    32  		}
    33  	}
    34  
    35  	return b
    36  }
    37  
    38  func main() {
    39  	cfg, err := config.LoadConfigFromDefaultLocations()
    40  	if err != nil {
    41  		fmt.Fprintln(os.Stderr, "failed to load config", err.Error())
    42  		os.Exit(2)
    43  	}
    44  
    45  	// Attaching the mutation function onto modelgen plugin
    46  	p := modelgen.Plugin{
    47  		MutateHook: mutateHook,
    48  	}
    49  
    50  	err = api.Generate(cfg,
    51  		api.NoPlugins(),
    52  		api.AddPlugin(&p),
    53  	)
    54  	if err != nil {
    55  		fmt.Fprintln(os.Stderr, err.Error())
    56  		os.Exit(3)
    57  	}
    58  }
    59  ```
    60  
    61  Now fields from generated models will contain a additional tag `orm_binding`.
    62  
    63  This schema:
    64  
    65  ```graphql
    66  type Object {
    67      field1: String
    68      field2: Int
    69  }
    70  ```
    71  
    72  Will gen generated into:
    73  
    74  ```go
    75  type Object struct {
    76  	field1 *string  `json:"field1" orm_binding:"Object.field1"`
    77  	field2 *int     `json:"field2" orm_binding:"Object.field2"`
    78  }
    79  ```