gendata.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package dartgen
  2. import (
  3. "os"
  4. "text/template"
  5. "git.i2edu.net/i2/go-zero/tools/goctl/api/spec"
  6. )
  7. const dataTemplate = `// --{{with .Info}}{{.Title}}{{end}}--
  8. {{ range .Types}}
  9. class {{.Name}}{
  10. {{range .Members}}
  11. /// {{.Comment}}
  12. final {{.Type}} {{lowCamelCase .Name}};
  13. {{end}}
  14. {{.Name}}({ {{range .Members}}
  15. this.{{lowCamelCase .Name}},{{end}}
  16. });
  17. factory {{.Name}}.fromJson(Map<String,dynamic> m) {
  18. return {{.Name}}({{range .Members}}
  19. {{lowCamelCase .Name}}: {{if isDirectType .Type}}m['{{tagGet .Tag "json"}}']{{else if isClassListType .Type}}(m['{{tagGet .Tag "json"}}'] as List<dynamic>).map((i) => {{getCoreType .Type}}.fromJson(i)){{else}}{{.Type}}.fromJson(m['{{tagGet .Tag "json"}}']){{end}},{{end}}
  20. );
  21. }
  22. Map<String,dynamic> toJson() {
  23. return { {{range .Members}}
  24. '{{tagGet .Tag "json"}}': {{if isDirectType .Type}}{{lowCamelCase .Name}}{{else if isClassListType .Type}}{{lowCamelCase .Name}}.map((i) => i.toJson()){{else}}{{lowCamelCase .Name}}.toJson(){{end}},{{end}}
  25. };
  26. }
  27. }
  28. {{end}}
  29. `
  30. func genData(dir string, api *spec.ApiSpec) error {
  31. err := os.MkdirAll(dir, 0o755)
  32. if err != nil {
  33. return err
  34. }
  35. err = genTokens(dir)
  36. if err != nil {
  37. return err
  38. }
  39. file, err := os.OpenFile(dir+api.Service.Name+".dart", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
  40. if err != nil {
  41. return err
  42. }
  43. defer file.Close()
  44. t := template.New("dataTemplate")
  45. t = t.Funcs(funcMap)
  46. t, err = t.Parse(dataTemplate)
  47. if err != nil {
  48. return err
  49. }
  50. return t.Execute(file, api)
  51. }
  52. func genTokens(dir string) error {
  53. path := dir + "tokens.dart"
  54. if fileExists(path) {
  55. return nil
  56. }
  57. tokensFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
  58. if err != nil {
  59. return err
  60. }
  61. defer tokensFile.Close()
  62. _, err = tokensFile.WriteString(tokensFileContent)
  63. return err
  64. }