middleware_get_list.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package got
  2. import (
  3. // . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/gen"
  4. "text/template"
  5. . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
  6. G "github.com/dave/jennifer/jen"
  7. )
  8. var (
  9. getListStmtsTmpl *template.Template
  10. getListStmtsErr error
  11. )
  12. func init() {
  13. getListStmtsTmpl, getListStmtsErr = ParseTemplate(`
  14. var (
  15. ntoken string
  16. entities = []*models.{{.entity}}{}
  17. count = 0
  18. values = ctx.Values()
  19. )
  20. values.Set("entities", &entities)
  21. options := values.Get("$filter").(*api.Filter)
  22. options.DB = "{{.dbName}}"
  23. options.Collection = "{{.collectionName}}"
  24. options.Entities = &entities
  25. if err = t.Fields(options); err != nil {
  26. return
  27. }
  28. {{if .preconditions}}
  29. if _, err = executeAction(
  30. ctx,
  31. {{.preconditions}},
  32. ); err != nil {
  33. return
  34. }
  35. {{end}}
  36. if _, err = models.Api.FindMany(options); err != nil {
  37. return
  38. }
  39. {{if .beforeResponse}}
  40. if resp, err = executeAction(
  41. ctx,
  42. {{.beforeResponse}},
  43. ); err != nil || resp != nil {
  44. return
  45. }
  46. {{end}}
  47. resp = &models.{{.responseStruct}}{
  48. Itens: entities,
  49. NextPageToken: ntoken,
  50. ResultSizeEstimate: count,
  51. }
  52. return`)
  53. if getListStmtsErr != nil {
  54. panic(getListStmtsErr)
  55. }
  56. }
  57. var (
  58. GenGetStmtsList = &Middleware{
  59. Id: "get_list",
  60. Type: "method",
  61. Fn: func(ctx *MiddlewareContext) error {
  62. var (
  63. project = ctx.Project
  64. method = ctx.Method
  65. responseStruct = method.Response
  66. response = project.ResponseEntity(responseStruct)
  67. )
  68. if response.IsGeneric {
  69. GenFromGenericModel(project, response)
  70. responseStruct = response.NewName
  71. }
  72. var (
  73. context = map[string]interface{}{
  74. "dbName": project.GetEntityDB(method.Entity),
  75. "collectionName": project.GetCollection(method.Entity),
  76. "beforeSend": method.Hook("beforeSend"),
  77. "beforeFind": method.Hook("beforeFind"),
  78. "entity": method.Entity,
  79. "responseStruct": responseStruct,
  80. "preconditions": parseMethodActions(method.Preconditions),
  81. "beforeResponse": parseMethodActions(method.BeforeResponse),
  82. }
  83. )
  84. // Nome do metodo que verifica se a entidade tem dependencias
  85. out, _ := TemplateToString(getListStmtsTmpl, context)
  86. ctx.Statement.Block(G.Id(out)).Line()
  87. return nil
  88. },
  89. }
  90. )