You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.7 KiB

2 years ago
package main
import (
"fmt"
2 years ago
protogen2 "git.diulo.com/mogfee/protoc-gen-kit/pkg/protogen"
2 years ago
"google.golang.org/protobuf/compiler/protogen"
"strings"
)
func main() {
2 years ago
u := &Kit{}
2 years ago
protogen.Options{}.Run(u.Generate)
}
type Kit struct {
}
func (u *Kit) Generate(plugin *protogen.Plugin) error {
if len(plugin.Files) < 1 {
return nil
}
2 years ago
2 years ago
for _, f := range plugin.Files {
if len(f.Services) == 0 {
continue
}
fname := f.GeneratedFilenamePrefix + ".ts"
t := plugin.NewGeneratedFile(fname, f.GoImportPath)
2 years ago
t.P(`// @ts-ignore`)
2 years ago
t.P(`import {Config,http} from "./http";`)
2 years ago
for _, s := range f.Messages {
t.P(`export interface `, s.Desc.Name(), ` {`)
for _, vv := range s.Fields {
common := strings.TrimSpace(vv.Comments.Leading.String())
if common != "" {
t.P(` `, common)
}
typ := []string{}
isRequired := ":"
if vv.Desc.IsMap() {
fields := vv.Desc.Message().Fields()
typ = append(typ, fmt.Sprintf(`{ [key: %s]: %s }`, getType(fields.Get(0).Kind().String()), getType(fields.Get(1).Kind().String())))
} else if vv.Desc.Kind().String() == "message" {
fullName := fmt.Sprintf("%v", vv.Desc.Message().FullName())
if strings.HasPrefix(fullName, "google.protobuf") && strings.HasSuffix(fullName, "Value") {
isRequired = "?:"
}
typ = append(typ, getType(fmt.Sprintf("%v", vv.Desc.Message().Name())))
} else {
typ = append(typ, getType(vv.Desc.Kind().String()))
}
if vv.Desc.IsList() {
typ = append(typ, "[]")
}
t.P(` `, vv.Desc.JSONName(), isRequired, ` `, strings.Join(typ, ""))
}
t.P(`}`)
t.P()
}
2 years ago
for _, s := range f.Services {
t.P(`export class `, s.Desc.Name(), `Service{`)
for _, m := range s.Methods {
method, path := protogen2.GetProtoMethod(m)
if method == "" {
continue
}
common := strings.TrimSpace(m.Comments.Leading.String())
if common != "" {
t.P(` `, common)
}
t.P(getInd(1), `static async `, m.Desc.Name(), `(data :`, m.Input.Desc.Name(), `, param?: Config<loginRequest>):Promise<`, m.Output.Desc.Name(), `>{`)
t.P(getInd(2), `return http<`, m.Input.Desc.Name(), `, `, m.Output.Desc.Name(), `>('`, path, `', {`)
t.P(getInd(3), `...param,`)
t.P(getInd(3), `data: data,`)
t.P(getInd(3), `method:'`, method, `'`)
t.P(getInd(2), `})`)
t.P(getInd(1), `}`)
}
t.P(`}`)
}
2 years ago
}
return nil
}
2 years ago
func getInd(i int) string {
return strings.Repeat(` `, i)
}
2 years ago
func getType(key string) string {
mps := map[string]string{
"int32": "number",
"bytes": "Uint8Array",
"Int32Value": "number",
"StringValue": "string",
"bool": "boolean",
}
if v, ok := mps[key]; ok {
return v
}
return key
}