Skip to content

Instantly share code, notes, and snippets.

@aight8
Created October 21, 2020 12:55
Show Gist options
  • Save aight8/ac072ad3bb76c945ee3fdbedb9d50658 to your computer and use it in GitHub Desktop.
Save aight8/ac072ad3bb76c945ee3fdbedb9d50658 to your computer and use it in GitHub Desktop.
golang ent template: Create Node By Required field method
{{define "node"}}
// ...
{{range $node := $.Nodes}}
{{$requiredFieldIndices := xrange 0}}
{{range $index, $field := $node.Fields}}
{{if and (not $field.Optional) (not $field.Default) (not $field.Immutable) -}}
{{$requiredFieldIndices = append $requiredFieldIndices $index}}
{{end}}
{{end}}
{{$requiredEdgeIndices := xrange 0}}
{{range $index, $edge := $node.Edges}}
{{if and (not $edge.Optional) -}}
{{$requiredEdgeIndices = append $requiredEdgeIndices $index}}
{{end}}
{{end}}
func ({{$r}} {{$createTypePtr}}) SetRequiredFields(
{{range $index := $requiredFieldIndices -}}
{{$field := index $node.Fields $index -}}
{{if $field.Unique}}{{camel (printf "%s%s" "unique_" $field.BuilderField)}}{{else}}{{camel $field.BuilderField}}{{end}} {{$field.Type}},
{{end -}}
{{- range $index := $requiredEdgeIndices -}}
{{- $e := index $node.Edges $index -}}
{{$idsParams := print (singular $e.BuilderField | camel) "IDs"}}{{if $e.Unique}}{{$idsParams = print (camel $e.BuilderField) "ID"}}{{end}}
{{$idsParams}} {{if not $e.Unique}}[]{{end}}{{$e.Type.ID.Type}},
{{- end}}
) {{$createTypePtr}} {
{{- range $index := $requiredFieldIndices}}
{{$field := index $node.Fields $index -}}
{{$r}}.Set{{$field.StructField}}(
{{- if $field.Unique}}{{camel (printf "%s%s" "unique_" $field.BuilderField)}}{{else}}{{camel $field.BuilderField}}{{end -}}
)
{{- end -}}
{{- range $index := $requiredEdgeIndices -}}
{{- $e := index $node.Edges $index -}}
{{$op := "add"}}{{if $e.Unique}}{{$op = "set"}}{{end}}
{{$idsFunc := print (pascal $op) (singular $e.Name | pascal) "IDs"}}{{if $e.Unique}}{{$idsFunc = print (pascal $op) (pascal $e.Name) "ID"}}{{end}}
{{- $idsParams := print (singular $e.BuilderField | camel) "IDs"}}{{if $e.Unique}}{{$idsParams = print (camel $e.BuilderField) "ID"}}{{end -}}
{{- $r}}.{{$idsFunc}}({{$idsParams}}{{if not $e.Unique}}...{{end}})
{{- end}}
return {{$r}}
}
// ...
{{end}}
// ...
{{end}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment