middleware_undelete.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package got
  2. import (
  3. "text/template"
  4. . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
  5. G "github.com/dave/jennifer/jen"
  6. )
  7. const ()
  8. var (
  9. undeleteStmtsTmpl, hasDepUndeleteStmtsTmpl *template.Template
  10. undeleteStmtsErr error
  11. )
  12. func init() {
  13. undeleteStmtsTmpl, undeleteStmtsErr = ParseTemplate(`
  14. var (
  15. patchs = &models.{{.entity}}Patchs{Set: &models.{{.entity}}Input{}}
  16. entity = patchs.Set
  17. )
  18. values := ctx.Values()
  19. values.Set("patchs", patchs)
  20. values.Set("entity", entity)
  21. user := values.Get("$user.ref").(*models.UserReference)
  22. entity.SetDeleted(false)
  23. entity.LastUpdate = api.NowUnix()
  24. entity.UpdatedBy = user
  25. {{if .preconditions}}
  26. if _, err = executeAction(
  27. ctx,
  28. {{.preconditions}},
  29. ); err != nil {
  30. return
  31. }
  32. {{end}}
  33. options := values.Get("$filter").(*api.Filter)
  34. options.DB = "{{.dbName}}"
  35. options.Collection = "{{.collectionName}}"
  36. options.Patchs, options.Options = patchs.Patch()
  37. if _, err = models.Api.PatchOne(options); err != nil {
  38. return
  39. }
  40. {{if .beforeResponse}}
  41. if resp, err = executeAction(
  42. ctx,
  43. {{.beforeResponse}},
  44. ); err != nil || resp != nil {
  45. return
  46. }
  47. {{end}}
  48. resp = ""
  49. return`)
  50. if undeleteStmtsErr != nil {
  51. panic(undeleteStmtsErr)
  52. }
  53. }
  54. var (
  55. GenUndeleteStmts = &Middleware{
  56. Id: "undelete",
  57. Type: "method",
  58. Fn: func(ctx *MiddlewareContext) error {
  59. var (
  60. project = ctx.Project
  61. method = ctx.Method
  62. dbName = project.GetEntityDB(method.Entity)
  63. collectionName = project.GetCollection(method.Entity)
  64. relations = SR.Get(method.Entity)
  65. relationCount = len(relations)
  66. dependenceMethod = BASE_HAS_DEPENDE + method.Entity
  67. // createDepFunc = SR.Has(method.Entity)
  68. beforeSend = method.Hook("beforeSend")
  69. beforePersist = method.Hook("beforePersist")
  70. context = map[string]interface{}{
  71. "dbName": dbName,
  72. "collectionName": collectionName,
  73. "entity": method.Entity,
  74. // "createDepFunc": createDepFunc,
  75. "relationCount": relationCount,
  76. "relations": relations,
  77. "dependenceMethod": dependenceMethod,
  78. "beforePersist": beforePersist,
  79. "beforeSend": beforeSend,
  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(undeleteStmtsTmpl, context)
  86. ctx.Statement.Block(G.Id(out)).Line()
  87. // if createDepFunc {
  88. // out, _ = TemplateToString(hasDepUndeleteStmtsTmpl, context)
  89. // afterMethod.Id(out)
  90. // }
  91. return nil
  92. },
  93. }
  94. )
  95. // import (
  96. // "fmt"
  97. // "strings"
  98. // . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
  99. // G "github.com/dave/jennifer/jen"
  100. // // "github.com/davecgh/go-spew/spew"
  101. // )
  102. // var (
  103. // GenUndeleteStmts = &Middleware{
  104. // Id: "undelete",
  105. // Type: "method",
  106. // Fn: func(ctx *MiddlewareContext) error {
  107. // var (
  108. // // UpdateRelationRotine *G.Statement
  109. // method = ctx.Method
  110. // // updRelation = UPDATE_RELATION + method.Entity
  111. // // createUpdateRelation = false
  112. // entity = method.Request
  113. // responseEntity = GenericPart.ReplaceAllString(method.Response, "")
  114. // )
  115. // if entity == "" {
  116. // panic("Modelo de request não definido em UpdateStmt!")
  117. // }
  118. // if responseEntity == "" {
  119. // panic("Modelo de response não definido!")
  120. // }
  121. // ctx.Statement.Block(
  122. // // Declaracao das variaveis
  123. // G.Var().Defs(
  124. // // G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  125. // // G.Id("patchs").Op("=").Op("&").Id(entity).Values(),
  126. // G.Id("patchs").Op("=").Op("&").Id(fmt.Sprintf("%sPatchs", method.Entity)).Values(
  127. // G.Id("Set").Op(": &").Id(entity).Values(),
  128. // ),
  129. // // G.Id("patchs").Op("=").Id(entity).Values(),
  130. // G.Id("entity = patchs.Set"),
  131. // G.Do(func(s *G.Statement) {
  132. // if method.BeforePersistAction {
  133. // s.Id("fn").Func().Call().Op("*").Qual(API_ERROR, "Error")
  134. // }
  135. // }),
  136. // ).Line(),
  137. // // G.Id("fmt.Println(`era o undelete`)").Line(),
  138. // // Fazendo o parse do body
  139. // // G.If(
  140. // // G.Id("err").Op("=").Qual(API_URL, "ReadJson").Call(G.Id("ctx"), G.Id("patchs")),
  141. // // G.Id("err").Op("!=").Id("nil"),
  142. // // ).Block(
  143. // // // G.Id("api").Dot("Falha").Call(
  144. // // // G.Id("ctx"),
  145. // // // G.Id("api").Dot("ErrGeneral"),
  146. // // // G.Id("err").Dot("Error").Call(),
  147. // // // G.Nil(),
  148. // // // ),
  149. // // // G.Return(G.Id("err")),
  150. // // G.Return(),
  151. // // ),
  152. // // G.Do(func(s *G.Statement) {
  153. // // entity := ctx.Project.EntityDesc(method.Entity)
  154. // // if entity != nil && entity.HasMode {
  155. // // s.Add(G.Id(`entity.SetMode("create")`))
  156. // // }
  157. // // }),
  158. // // G.If(
  159. // // G.Id("err").Op("=").Qual(API_URL, "Validate").Call(G.Id("entity")),
  160. // // G.Id("err").Op("!=").Id("nil"),
  161. // // ).Block(
  162. // // // G.Return(G.Id("err")),
  163. // // G.Return(),
  164. // // ).Line(),
  165. // // Captura a base de values
  166. // G.Id("values").Op(":=").Id("ctx").Dot("Values").Call(),
  167. // G.Id("values").Dot("Set").Call(G.Lit("patchs"), G.Id("patchs")),
  168. // G.Id("entity.SetDeleted(false)"),
  169. // // Gera as atribuicoes de variaveis que seram atualizadas (usuario e ultimo update quando existir)
  170. // G.Do(func(part *G.Statement) {
  171. // entity := ctx.Project.GetSchema(method.Entity)
  172. // user := false
  173. // for _, prop := range entity.Properties {
  174. // if def, ok := prop.Autogenerate["update"]; ok {
  175. // switch def.Type {
  176. // case "user":
  177. // if !user {
  178. // part.Add(G.Id(`user := values.Get("$user.ref").(*UserReference)`).Line())
  179. // user = true
  180. // }
  181. // part.Add(G.Id("entity").Dot(strings.Title(prop.ID)).Op("=").Id("user").Line())
  182. // case "now":
  183. // part.Add(G.Id("entity").Dot(strings.Title(prop.ID)).Op("=").Qual("time", "Now").Call().Id(".Unix()").Line())
  184. // }
  185. // }
  186. // }
  187. // }).Line(),
  188. // // Carrega o filtro do contexto para adicionar a entidade
  189. // G.Id("filter").Op(":=").Id("values").Dot("Get").Call(
  190. // G.Lit("$filter"),
  191. // ).Assert(G.Op("*").Qual(API_URL, "Filter")).Line(),
  192. // // Adiciona a entidade
  193. // G.Id("filter").Dot("DB").Op("=").Lit(ctx.Project.GetEntityDB(method.Entity)),
  194. // G.Id("filter").Dot("Collection").Op("=").Lit(ctx.Project.GetCollection(method.Entity)),
  195. // G.Do(func(s *G.Statement) {
  196. // if method.BeforePersistAction {
  197. // fnName := fmt.Sprintf("Before%s%s", strings.Title(method.ID), method.Entity)
  198. // part := s.Comment("Chama uma função onde são descritas as ações executadas antes da entidade ser persistida.").Line()
  199. // part.If(
  200. // G.List(G.Id("fn"), G.Id("err")).Op("=").Id(fnName).Call(G.Id("ctx"), G.Id("patchs")),
  201. // G.Id("err").Op("!=").Id("nil"),
  202. // ).Block(G.Return())
  203. // }
  204. // }),
  205. // G.Id("filter").Dot("Patchs").Op("=").Id("patchs.Patch()").Line(),
  206. // // Inseri a entidade na coleção e verifica se a operação ocorreu com exito
  207. // G.If(
  208. // G.List(G.Id("_"), G.Id("err")).Op("=").Id("Models").Dot("PatchOne").Call(
  209. // // G.Lit(ctx.Project.GetCollection(method.Entity)),
  210. // G.Id("filter"),
  211. // ),
  212. // G.Id("err").Op("!=").Id("nil"),
  213. // ).Block(
  214. // // G.Id("api").Dot("Falha").Call(
  215. // // G.Id("ctx"),
  216. // // G.Id("api").Dot("ErrGeneral"),
  217. // // G.Id("err").Dot("Error").Call(),
  218. // // G.Nil(),
  219. // // ),
  220. // // bson.IsObjectIdHex(m.Id.Hex())
  221. // // G.Return(G.Id("err")),
  222. // G.Return(),
  223. // ),
  224. // G.Do(func(s *G.Statement) {
  225. // if method.BeforePersistAction {
  226. // part := s.Comment("Chama uma função onde são descritas as ações executadas após a entidade ser persistida.").Line()
  227. // part.If(
  228. // G.Id("err").Op("=").Id("fn").Call(),
  229. // G.Id("err").Op("!=").Id("nil"),
  230. // ).Block(G.Return())
  231. // }
  232. // }),
  233. // G.Id("resp").Op("=").Lit(""),
  234. // // Cria a rotina de atualização de relacionamentos
  235. // // G.Do(func(s *G.Statement) {
  236. // // if SR.Has(method.Entity) {
  237. // // createUpdateRelation = true
  238. // // s.Comment("Cria uma thread que executa a atualizaca das referências.").Line().Go().Func().Params().Block(
  239. // // G.Id(updRelation).Call(G.Id("filter")),
  240. // // ).Call()
  241. // // }
  242. // // }),
  243. // // Envia a resposta pro usuario em caso de sucesso
  244. // // G.Line().Id("resp").Op("=").Id(responseEntity).Values(G.Dict{
  245. // // G.Id("Entity"): G.Id("entity"),
  246. // // }),
  247. // // G.Line().Id("resp").Op("=").Id("entity"),
  248. // // G.Return(G.Nil()),
  249. // G.Return(),
  250. // ).Line()
  251. // return nil
  252. // },
  253. // }
  254. // )