github.com/woocoos/entco@v0.0.0-20240411071658-1e7b23d4df15/genx/gql/template.go (about) 1 package gql 2 3 import ( 4 "embed" 5 "github.com/99designs/gqlgen/codegen" 6 "github.com/vektah/gqlparser/v2/ast" 7 "go/types" 8 "strings" 9 "text/template" 10 ) 11 12 var ( 13 //go:embed template 14 templateDir embed.FS 15 funcs = template.FuncMap{ 16 "hasPrefix": strings.HasPrefix, 17 "isEntCreate": isEntCreate, 18 "isEntUpdate": isEntUpdate, 19 "isEntDelete": isEntDelete, 20 "findCreateEntArg": findCreateEntArgs, 21 "findUpdateEntArg": findUpdateEntArgs, 22 "toLower": strings.ToLower, // some as ent 23 "trimSuffix": strings.TrimSuffix, 24 "trimPrefix": strings.TrimPrefix, 25 } 26 ) 27 28 type MutationType int 29 30 const ( 31 MutationCreate MutationType = iota 32 MutationUpdate 33 MutationDelete 34 ) 35 36 func isEntCreate(field *codegen.Field) bool { 37 if field.Object.Definition.Name != "Mutation" { 38 return false 39 } 40 if len(field.Args) != 1 { 41 return false 42 } 43 if field.Args[0].TypeReference.Definition.Kind != ast.InputObject { 44 return false 45 } 46 switch { 47 case strings.HasPrefix(field.GoFieldName, "Create"): 48 return true 49 } 50 return false 51 } 52 53 func isEntUpdate(field *codegen.Field) bool { 54 if field.Object.Definition.Name != "Mutation" { 55 return false 56 } 57 if len(field.Args) != 2 { 58 return false 59 } 60 switch { 61 case strings.HasPrefix(field.GoFieldName, "Update"): 62 return true 63 } 64 return false 65 } 66 67 func isEntDelete(field *codegen.Field) bool { 68 if field.Object.Definition.Name != "Mutation" { 69 return false 70 } 71 72 switch { 73 case strings.HasPrefix(field.GoFieldName, "Delete"): 74 // cannot bool pointer 75 if field.TypeReference.GO.String() != types.Typ[types.Bool].String() { 76 return false 77 } 78 return true 79 } 80 return false 81 } 82 83 func findCreateEntArgs(field *codegen.Field) string { 84 return findEntArg(field, MutationCreate) 85 } 86 87 func findUpdateEntArgs(field *codegen.Field) (input string) { 88 return findEntArg(field, MutationUpdate) 89 } 90 91 func findEntArg(field *codegen.Field, mt MutationType) (input string) { 92 entTypeName := field.TypeReference.Definition.Name 93 for _, arg := range field.Args { 94 switch arg.TypeReference.Definition.Kind { 95 case ast.InputObject: 96 switch mt { 97 case MutationCreate, MutationUpdate, MutationDelete: 98 if strings.HasSuffix(arg.Type.NamedType, entTypeName+"Input") { 99 input = arg.Name 100 return 101 } 102 } 103 } 104 } 105 return 106 } 107 108 func isPagination(field *codegen.Field) bool { 109 if len(field.Args) != 6 { 110 return false 111 } 112 count := 0 113 for _, arg := range field.Args { 114 switch arg.Name { 115 case "first", "after", "last", "before", "where", "orderBy": 116 count++ 117 } 118 } 119 return count == 6 120 }