forked from go-kratos/kratos
/
template.go
122 lines (106 loc) · 2.55 KB
/
template.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package gateway
import (
"bytes"
"html/template"
)
//nolint:lll
var serviceTemplate = `
{{- /* delete empty line */ -}}
package graph
import (
{{- if .UseContext }}
"context"
{{- end }}
{{- if .UseIO }}
"io"
{{- end }}
"github.com/go-kratos/kratos/v2/log"
pb "{{ .Package }}"
{{- if .GoogleEmpty }}
"google.golang.org/protobuf/types/known/emptypb"
{{- end }}
"smart-home-api/app/gateway/internal/child"
)
type (
{{ .Service }}Graphql struct {
{{ .Service }}Client pb.{{ .Service }}Client
logger *log.Helper
}
{{ range .Methods }}
{{ .Request }} struct {}
{{ .Reply }} struct {}
{{- end }}
)
func New{{ .Service }}Graphql(d *child.Data, logger log.Logger) *{{ .Service }}Graphql {
return &{{ .Service }}Graphql{
{{ .Service }}Client: d.{{ .Service }}Client(),
logger: log.NewHelper(log.With(logger, "module", "graph/{{ .Service }}")),
}
}
{{- $s1 := "google.protobuf.Empty" }}
{{ range .Methods }}
func (l *{{ .Service }}Graphql) {{ .Name }}(ctx context.Context, args struct {
In *{{ .Request }}
}) (*{{ .Reply }}, error) {
// TODO use args.In params
res, err := l.{{ .Service }}Client.{{ .Name }}(ctx, &{{ if eq .Request $s1 }}emptypb.Empty{}{{ else }}pb.{{ .Request }}{}{{ end }})
if err != nil {
l.logger.Errorf("{{ .Name }} err: +v%", err)
return nil, err
}
l.logger.Debugf("{{ .Name }} res: +v%", res)
return &{{ .Reply }}{
// TODO
}, nil
}
{{- end }}
`
type MethodType uint8
const (
unaryType MethodType = 1
twoWayStreamsType MethodType = 2
requestStreamsType MethodType = 3
returnsStreamsType MethodType = 4
)
// Service is a proto service.
type Service struct {
Package string
Service string
Methods []*Method
GoogleEmpty bool
UseIO bool
UseContext bool
}
// Method is a proto method.
type Method struct {
Service string
Name string
Request string
Reply string
// type: unary or stream
Type MethodType
}
func (s *Service) execute() ([]byte, error) {
const empty = "google.protobuf.Empty"
buf := new(bytes.Buffer)
for _, method := range s.Methods {
if (method.Type == unaryType && (method.Request == empty || method.Reply == empty)) ||
(method.Type == returnsStreamsType && method.Request == empty) {
s.GoogleEmpty = true
}
if method.Type == twoWayStreamsType || method.Type == requestStreamsType {
s.UseIO = true
}
if method.Type == unaryType {
s.UseContext = true
}
}
tmpl, err := template.New("service").Parse(serviceTemplate)
if err != nil {
return nil, err
}
if err := tmpl.Execute(buf, s); err != nil {
return nil, err
}
return buf.Bytes(), nil
}