You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/tools/goctl/api/tsgen/gencomponents.go

65 lines
1.3 KiB
Go

4 years ago
package tsgen
import (
_ "embed"
4 years ago
"path"
"strings"
"text/template"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
4 years ago
)
//go:embed components.tpl
var componentsTemplate string
4 years ago
func genComponents(dir string, api *spec.ApiSpec) error {
types := api.Types
4 years ago
if len(types) == 0 {
return nil
}
val, err := buildTypes(types)
4 years ago
if err != nil {
return err
}
outputFile := apiutil.ComponentName(api) + ".ts"
filename := path.Join(dir, outputFile)
if err := pathx.RemoveIfExist(filename); err != nil {
4 years ago
return err
}
fp, created, err := apiutil.MaybeCreateFile(dir, ".", outputFile)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
t := template.Must(template.New("componentsTemplate").Parse(componentsTemplate))
return t.Execute(fp, map[string]string{
"componentTypes": val,
})
}
func buildTypes(types []spec.Type) (string, error) {
4 years ago
var builder strings.Builder
first := true
for _, tp := range types {
if first {
first = false
} else {
builder.WriteString("\n")
}
if err := writeType(&builder, tp); err != nil {
return "", apiutil.WrapErr(err, "Type "+tp.Name()+" generate error")
4 years ago
}
}
return builder.String(), nil
}