validator.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package parser
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "zero/core/stringx"
  7. "zero/tools/goctl/api/spec"
  8. "zero/tools/goctl/api/util"
  9. )
  10. func (p *Parser) validate(api *spec.ApiSpec) (err error) {
  11. var builder strings.Builder
  12. for _, tp := range api.Types {
  13. if ok, name := p.validateDuplicateProperty(tp); !ok {
  14. fmt.Fprintf(&builder, `duplicate property "%s" of type "%s"`+"\n", name, tp.Name)
  15. }
  16. }
  17. if ok, info := p.validateDuplicateRouteHandler(api); !ok {
  18. fmt.Fprintf(&builder, info)
  19. }
  20. if len(builder.String()) > 0 {
  21. return errors.New(builder.String())
  22. }
  23. return nil
  24. }
  25. func (p *Parser) validateDuplicateProperty(tp spec.Type) (bool, string) {
  26. var names []string
  27. for _, member := range tp.Members {
  28. if stringx.Contains(names, member.Name) {
  29. return false, member.Name
  30. } else {
  31. names = append(names, member.Name)
  32. }
  33. }
  34. return true, ""
  35. }
  36. func (p *Parser) validateDuplicateRouteHandler(api *spec.ApiSpec) (bool, string) {
  37. var names []string
  38. for _, r := range api.Service.Routes {
  39. handler, ok := util.GetAnnotationValue(r.Annotations, "server", "handler")
  40. if !ok {
  41. return false, fmt.Sprintf("missing handler annotation for %s", r.Path)
  42. }
  43. if stringx.Contains(names, handler) {
  44. return false, fmt.Sprintf(`duplicated handler for name "%s"`, handler)
  45. } else {
  46. names = append(names, handler)
  47. }
  48. }
  49. return true, ""
  50. }