-
Notifications
You must be signed in to change notification settings - Fork 5
/
mutation_resolver_generator.go
92 lines (79 loc) · 2.43 KB
/
mutation_resolver_generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package generator
import (
"errors"
"fmt"
"go/types"
"os"
"path"
"text/template"
"github.com/schartey/dgraph-lambda-go/codegen/config"
"github.com/schartey/dgraph-lambda-go/codegen/parser"
"github.com/schartey/dgraph-lambda-go/codegen/rewriter"
)
func generateMutationResolvers(c *config.Config, r *rewriter.Rewriter) error {
if c.ResolverFilename == "resolver" {
fileName := path.Join(c.Resolver.Dir, "mutation.resolver.go")
f, err := os.Create(fileName)
if err != nil {
fmt.Println(err.Error())
}
defer f.Close()
pkgs := make(map[string]*types.Package)
for _, m := range c.ParsedTree.ResolverTree.Mutations {
if m.Return.TypeName.Exported() {
pkgs[m.Return.TypeName.Pkg().Name()] = m.Return.TypeName.Pkg()
}
for _, f := range m.Arguments {
if f.TypeName.Exported() {
pkgs[f.GoType.TypeName.Pkg().Name()] = f.GoType.TypeName.Pkg()
}
}
}
if len(c.ParsedTree.ResolverTree.Mutations) > 0 {
pkgs["context"] = types.NewPackage("context", "context")
pkgs["api"] = types.NewPackage("github.com/schartey/dgraph-lambda-go/api", "api")
}
err = mutationResolverTemplate.Execute(f, struct {
MutationResolvers map[string]*parser.Mutation
Rewriter *rewriter.Rewriter
Packages map[string]*types.Package
PackageName string
}{
MutationResolvers: c.ParsedTree.ResolverTree.Mutations,
Rewriter: r,
Packages: pkgs,
PackageName: c.Resolver.Package,
})
if err != nil {
return err
}
return nil
}
return errors.New("Resolver file pattern invalid")
}
var mutationResolverTemplate = template.Must(template.New("mutation-resolver").Funcs(template.FuncMap{
"ref": resolverRef,
"path": pkgPath,
"pointer": pointer,
"argsW": argsW,
"body": body,
"is": is,
}).Parse(`
package {{.PackageName}}
import(
{{- range $pkg := .Packages }}
"{{ $pkg | path }}"{{- end}}
)
/** Put these into resolvers.go or similar **/
type MutationResolver struct {
*Resolver
}
{{- range $mutationResolver := .MutationResolvers}}
func (q *MutationResolver) Mutation_{{$mutationResolver.Name}}(ctx context.Context, {{ $mutationResolver.Arguments | argsW }}, authHeader api.AuthHeader) (*{{$mutationResolver.Return | ref}}, error) { {{ body (printf "Mutation_%s" $mutationResolver.Name) $.Rewriter }}}
{{ end }}
{{- range $key, $depBody := .Rewriter.DeprecatedBodies }}
{{ if is $key "Mutation_" }}
/* {{ $depBody }} */
{{ end }}
{{ end }}
`))