-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprotoc-gen-rpc-impl.go
executable file
·84 lines (69 loc) · 1.93 KB
/
protoc-gen-rpc-impl.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
package main
import (
"fmt"
"google.golang.org/protobuf/compiler/protogen"
)
func main() {
protogen.Options{}.Run(func(gen *protogen.Plugin) error {
for _, f := range gen.Files {
if !f.Generate {
continue
}
generateFile(gen, f)
}
return nil
})
}
func generateFile(gen *protogen.Plugin, file *protogen.File) {
if len(file.Services) == 0 {
return
}
filename := file.GeneratedFilenamePrefix + "_server.go"
g := gen.NewGeneratedFile(filename, file.GoImportPath)
g.P("// Code generated by protoc-gen-rpc-impl. DO NOT EDIT.")
g.P()
g.P("package ", file.GoPackageName)
g.P()
// Write imports
g.P("import (")
g.P(` "context"`)
g.P(` "db"`)
g.P(` "go.uber.org/zap"`)
g.P(")")
g.P()
// Generate implementation struct and methods for each service
for _, service := range file.Services {
generateServiceImplementation(g, service)
}
}
func generateServiceImplementation(g *protogen.GeneratedFile, service *protogen.Service) {
structName := service.GoName + "ServiceServer"
// Generate struct
g.P("type ", structName, " struct {")
g.P(" Unimplemented", service.GoName, "Server")
g.P(" PrismaClient *db.PrismaClient")
g.P(" Logger *zap.SugaredLogger")
g.P("}")
g.P()
// Constructor
g.P("func New", structName, "() *", structName, " {")
g.P(" return &", structName, "{}")
g.P("}")
g.P()
// Generate methods
for _, method := range service.Methods {
generateMethodImplementation(g, method, structName)
}
}
func generateMethodImplementation(g *protogen.GeneratedFile, method *protogen.Method, structName string) {
methodName := method.GoName
inputType := method.Input.GoIdent.GoName
outputType := method.Output.GoIdent.GoName
signature := fmt.Sprintf("func (s *%s) %s(ctx context.Context, req *%s) (*%s, error)",
structName, methodName, inputType, outputType)
g.P(signature, " {")
g.P(" // TODO: Implement ", methodName)
g.P(" return &", outputType, "{}, nil")
g.P("}")
g.P()
}