github.com/fortexxx/gqlgen@v0.10.3-0.20191216030626-ca5ea8b21ead/plugin/modelgen/models.gotpl (about)

     1  {{ reserveImport "context"  }}
     2  {{ reserveImport "fmt"  }}
     3  {{ reserveImport "io"  }}
     4  {{ reserveImport "strconv"  }}
     5  {{ reserveImport "time"  }}
     6  {{ reserveImport "sync"  }}
     7  {{ reserveImport "errors"  }}
     8  {{ reserveImport "bytes"  }}
     9  
    10  {{ reserveImport "github.com/vektah/gqlparser" }}
    11  {{ reserveImport "github.com/vektah/gqlparser/ast" }}
    12  {{ reserveImport "github.com/99designs/gqlgen/graphql" }}
    13  {{ reserveImport "github.com/99designs/gqlgen/graphql/introspection" }}
    14  
    15  {{- range $model := .Interfaces }}
    16  	{{ with .Description }} {{.|prefixLines "// "}} {{ end }}
    17  	type {{.Name|go }} interface {
    18  		Is{{.Name|go }}()
    19  	}
    20  {{- end }}
    21  
    22  {{ range $model := .Models }}
    23  	{{with .Description }} {{.|prefixLines "// "}} {{end}}
    24  	type {{ .Name|go }} struct {
    25  		{{- range $field := .Fields }}
    26  			{{- with .Description }}
    27  				{{.|prefixLines "// "}}
    28  			{{- end}}
    29  			{{ $field.Name|go }} {{$field.Type | ref}} `{{$field.Tag}}`
    30  		{{- end }}
    31  	}
    32  
    33  	{{- range $iface := .Implements }}
    34  		func ({{ $model.Name|go }}) Is{{ $iface|go }}() {}
    35  	{{- end }}
    36  {{- end}}
    37  
    38  {{ range $enum := .Enums }}
    39  	{{ with .Description }} {{.|prefixLines "// "}} {{end}}
    40  	type {{.Name|go }} string
    41  	const (
    42  	{{- range $value := .Values}}
    43  		{{- with .Description}}
    44  			{{.|prefixLines "// "}}
    45  		{{- end}}
    46  		{{ $enum.Name|go }}{{ .Name|go }} {{$enum.Name|go }} = {{.Name|quote}}
    47  	{{- end }}
    48  	)
    49  
    50  	var All{{.Name|go }} = []{{ .Name|go }}{
    51  	{{- range $value := .Values}}
    52  		{{$enum.Name|go }}{{ .Name|go }},
    53  	{{- end }}
    54  	}
    55  
    56  	func (e {{.Name|go }}) IsValid() bool {
    57  		switch e {
    58  		case {{ range $index, $element := .Values}}{{if $index}},{{end}}{{ $enum.Name|go }}{{ $element.Name|go }}{{end}}:
    59  			return true
    60  		}
    61  		return false
    62  	}
    63  
    64  	func (e {{.Name|go }}) String() string {
    65  		return string(e)
    66  	}
    67  
    68  	func (e *{{.Name|go }}) UnmarshalGQL(v interface{}) error {
    69  		str, ok := v.(string)
    70  		if !ok {
    71  			return fmt.Errorf("enums must be strings")
    72  		}
    73  
    74  		*e = {{ .Name|go }}(str)
    75  		if !e.IsValid() {
    76  			return fmt.Errorf("%s is not a valid {{ .Name }}", str)
    77  		}
    78  		return nil
    79  	}
    80  
    81  	func (e {{.Name|go }}) MarshalGQL(w io.Writer) {
    82  		fmt.Fprint(w, strconv.Quote(e.String()))
    83  	}
    84  
    85  {{- end }}