-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
93 lines (79 loc) · 2.55 KB
/
main.go
File metadata and controls
93 lines (79 loc) · 2.55 KB
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
package main
import (
"flag"
"fmt"
"strings"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/types/pluginpb"
)
func main() {
var flags flag.FlagSet
protogen.Options{
ParamFunc: flags.Set,
}.Run(func(gen *protogen.Plugin) error {
gen.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
for _, f := range gen.Files {
if !f.Generate {
continue
}
generateFile(gen, f)
}
return nil
})
}
func getBaseName(name string) string {
base_filename := name
base_filename = base_filename[0 : len(base_filename)-6]
return base_filename
}
func generateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
base_filename := getBaseName(file.Proto.GetName())
filename := fmt.Sprintf("%s_grpc_async.ts", base_filename)
m := make(map[string]bool)
m[base_filename] = true
for _, service := range file.Services {
for _, method := range service.Methods {
m[getBaseName(method.Input.Location.SourceFile)] = true
m[getBaseName(method.Output.Location.SourceFile)] = true
}
}
g := gen.NewGeneratedFile(filename, "")
g.P("// Code generated by protoc-gen-grpc-async. DO NOT EDIT.")
g.P()
g.P("import * as grpc from \"@grpc/grpc-js\";")
g.P("import * as gpb from \"./", base_filename, "_grpc_pb\";")
for k, _ := range m {
g.P("import * as ", k, "_pb from \"./", k, "_pb\";")
}
g.P()
for _, service := range file.Services {
g.P("export class Async", service.GoName, "Client {")
g.P(" private readonly client: gpb.", service.GoName, "Client;")
g.P()
g.P(" constructor(client: gpb.", service.GoName, "Client) {")
g.P(" this.client = client;")
g.P(" }")
for _, method := range service.Methods {
name := method.GoName
name = fmt.Sprintf("%s%s", strings.ToLower(name[0:1]), name[1:])
ins := fmt.Sprintf("%s_pb", getBaseName(method.Input.Location.SourceFile))
ons := fmt.Sprintf("%s_pb", getBaseName(method.Output.Location.SourceFile))
g.P()
g.P(" public async ", name, "(request: ", ins, ".", method.Input.GoIdent.GoName, "): Promise<", ons, ".", method.Output.GoIdent.GoName, "> {")
g.P(" return new Promise((resolve, reject) => {")
g.P(" this.client.", name, "(")
g.P(" request,")
g.P(" (err: grpc.ServiceError | null, value?: ", ons, ".", method.Output.GoIdent.GoName, ") => {")
g.P(" if (err) {")
g.P(" reject(err);")
g.P(" } else {")
g.P(" resolve(value!);")
g.P(" }")
g.P(" });")
g.P(" });")
g.P(" }")
}
g.P("}")
}
return g
}