genapi.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package dartgen
  2. import (
  3. "os"
  4. "text/template"
  5. "zero/core/logx"
  6. "zero/tools/goctl/api/spec"
  7. )
  8. const apiTemplate = `import 'api.dart';
  9. import '../data/{{with .Info}}{{.Title}}{{end}}.dart';
  10. {{with .Service}}
  11. /// {{.Name}}
  12. {{range .Routes}}
  13. /// --{{.Path}}--
  14. ///
  15. /// 请求: {{with .RequestType}}{{.Name}}{{end}}
  16. /// 返回: {{with .ResponseType}}{{.Name}}{{end}}
  17. Future {{pathToFuncName .Path}}( {{if ne .Method "get"}}{{with .RequestType}}{{.Name}} request,{{end}}{{end}}
  18. {Function({{with .ResponseType}}{{.Name}}{{end}}) ok,
  19. Function(String) fail,
  20. Function eventually}) async {
  21. await api{{if eq .Method "get"}}Get{{else}}Post{{end}}('{{.Path}}',{{if ne .Method "get"}}request,{{end}}
  22. ok: (data) {
  23. if (ok != null) ok({{with .ResponseType}}{{.Name}}{{end}}.fromJson(data));
  24. }, fail: fail, eventually: eventually);
  25. }
  26. {{end}}
  27. {{end}}`
  28. func genApi(dir string, api *spec.ApiSpec) error {
  29. e := os.MkdirAll(dir, 0755)
  30. if e != nil {
  31. logx.Error(e)
  32. return e
  33. }
  34. e = genApiFile(dir)
  35. if e != nil {
  36. logx.Error(e)
  37. return e
  38. }
  39. file, e := os.OpenFile(dir+api.Info.Title+".dart", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  40. if e != nil {
  41. logx.Error(e)
  42. return e
  43. }
  44. defer file.Close()
  45. t := template.New("apiTemplate")
  46. t = t.Funcs(funcMap)
  47. t, e = t.Parse(apiTemplate)
  48. if e != nil {
  49. logx.Error(e)
  50. return e
  51. }
  52. t.Execute(file, api)
  53. return nil
  54. }
  55. func genApiFile(dir string) error {
  56. path := dir + "api.dart"
  57. if fileExists(path) {
  58. return nil
  59. }
  60. apiFile, e := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  61. if e != nil {
  62. logx.Error(e)
  63. return e
  64. }
  65. defer apiFile.Close()
  66. apiFile.WriteString(apiFileContent)
  67. return nil
  68. }