middleware_get_one.go 1.8 KB

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