Skip to content

Commit

Permalink
optimize: avoid IsValid() (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
HeyJavaBean authored Jan 2, 2024
1 parent 6ff1ec6 commit 2779b23
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
19 changes: 17 additions & 2 deletions validator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import (

var Version string

var ValidMethodName string = "IsValid"

type generator struct {
config *config.Config
request *plugin.Request
Expand Down Expand Up @@ -67,9 +69,22 @@ func newGenerator(req *plugin.Request) (*generator, error) {
}
g.utils = golang.NewCodeUtils(lf)
g.utils.HandleOptions(req.GeneratorParameters)
if parseExtend(req.PluginParameters) {
ValidMethodName = "IsStructValid"
}

return g, nil
}

func parseExtend(params []string) bool {
for _, parameter := range params {
if strings.HasPrefix(parameter, "avoid_name") {
return true
}
}
return false
}

func (g *generator) write(str string) {
g.buffer.WriteString(str)
}
Expand Down Expand Up @@ -198,7 +213,7 @@ func (g *generator) generateBody(ast *tp.Thrift, resolver *golang.Resolver) erro
if err != nil {
return err
}
g.writeLinef("func (p *%s) IsValid() error {\n", st.GoName().String())
g.writeLinef("func (p *%s) "+ValidMethodName+"() error {\n", st.GoName().String())
g.indent()
for _, vc := range vcs {
switch vc.ValidationType {
Expand Down Expand Up @@ -282,7 +297,7 @@ func (g *generator) generateStructLikeFieldValidation(vc *ValidateContext) error
}
}
if !skip {
g.writeLinef("if err := %s.IsValid(); err != nil {\n", vc.Target)
g.writeLinef("if err := %s."+ValidMethodName+"(); err != nil {\n", vc.Target)
g.indent()
g.writeLinef("return fmt.Errorf(\"field %s not valid, %%w\", err)", vc.FieldName)
g.unindent()
Expand Down
4 changes: 2 additions & 2 deletions validator/validator_tpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package validator
var StructLikeValidate = `
{{define "StructLikeValidate"}}
{{- $TypeName := .Name | Identify}}
func (p *{{$TypeName}}) IsValid() bool {
func (p *{{$TypeName}}) ` + ValidMethodName + `() bool {
{{- ctxs := MkValidateContexts .Fields}}
{{- range .ctxs}}
{{template "FieldValidate" .}}
Expand Down Expand Up @@ -49,7 +49,7 @@ var FieldValidateStructLike = `
{{- else if eq . Annotation $StructLikeAnnotation.NotNil}}
{{- end}}
if !{{.Target}}.IsValid({{.Source}}) {
if !{{.Target}}.` + ValidMethodName + `({{.Source}}) {
return false
}
{{- end}}{{/* "FieldValidateStructLike" */}}
Expand Down
2 changes: 1 addition & 1 deletion version.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ func init() {
}

const (
Version = "v0.2.2"
Version = "v0.2.3"
)

0 comments on commit 2779b23

Please sign in to comment.