genapi.go 1.6 KB

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