resources.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. package got
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "strings"
  7. "sync"
  8. "time"
  9. . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
  10. G "github.com/dave/jennifer/jen"
  11. "github.com/davecgh/go-spew/spew"
  12. )
  13. type Middleware struct {
  14. Id string `json:"id"`
  15. Type string `json:"type"`
  16. Fn func(ctx *MiddlewareContext) error `json:"-"`
  17. }
  18. type MiddlewareContext struct {
  19. Project *Project
  20. Method *Method
  21. Statement *G.Statement
  22. Middleware *Middleware
  23. File *G.File
  24. }
  25. var (
  26. Middlewares = map[string]*Middleware{
  27. "post": GenCreateStmts,
  28. "put": GenUpdateStmts,
  29. "patch": GenPatchStmts,
  30. "delete": GenDeleteStmts,
  31. "get_one": GenGetStmtsOne,
  32. "pipe": GenPipeStmts,
  33. "filter": GenGetFilter,
  34. "get_list": GenGetStmtsList,
  35. "undelete": GenUndeleteStmts,
  36. "implement": GenImplement,
  37. }
  38. ResourceWG = sync.WaitGroup{}
  39. )
  40. func InitFile(file *G.File, resource *Resource, p *Project) {
  41. now := time.Now().UnixNano()
  42. // file.ImportAlias(
  43. // file.ImportName(
  44. // fmt.Sprintf("%s/%s/models", p.Custom["go.package.repository"].(string), p.Package),
  45. // "models",
  46. // )
  47. if _, defined := p.Custom["go.package.repository"]; !defined {
  48. panic("go.package.repository not defined in project.json")
  49. }
  50. file.Var().Defs(
  51. G.Id(fmt.Sprintf("_%s_spew_%d_ =", resource.Entity, now)).Qual("github.com/davecgh/go-spew/spew", "Dump"),
  52. G.Id(fmt.Sprintf("_%s_bson_%d_ *", resource.Entity, now)).Qual(BSON, "M"),
  53. G.Id(fmt.Sprintf("_%s_time_%d_ *", resource.Entity, now)).Qual("time", "Duration"),
  54. G.Id(fmt.Sprintf("_%s_error_%d_ *", resource.Entity, now)).Qual(API_ERROR, "Error"),
  55. G.Id(fmt.Sprintf("_%s_sync_%d_ *", resource.Entity, now)).Qual("sync", "WaitGroup"),
  56. G.Id(fmt.Sprintf("_%s_primitive_%d_ *", resource.Entity, now)).Qual("go.mongodb.org/mongo-driver/bson/primitive", "ObjectID"),
  57. G.Id(fmt.Sprintf("_%s_models_%d_ *", resource.Entity, now)).Qual(
  58. fmt.Sprintf("%s/build/%s/models", p.Custom["go.package.repository"].(string), p.Package),
  59. "Entity",
  60. ),
  61. G.Id(fmt.Sprintf("_%s_actions_%d_ *", resource.Entity, now)).Qual(
  62. fmt.Sprintf("%s/build/%s/actions", p.Custom["go.package.repository"].(string), p.Package),
  63. "Action",
  64. ),
  65. )
  66. file.Func().Id("init").Params().BlockFunc(func(s *G.Group) {
  67. for _, v := range resource.Formats {
  68. s.Add(G.Id("FormatSelection").Index(G.Lit(resource.ID + "." + v.Id)).Op("=").Lit(v.Fields))
  69. }
  70. })
  71. }
  72. func CreateDummy(p *Project, resource *Resource, method *Method) error {
  73. // Verifica se existe um arquivo na pasta de include.
  74. // Caso o arquivo não exista um novo arquivo é criado.
  75. // outputfile := fmt.Sprintf("%s/include/go/api_%s_%s.go", CurrentDirectory, strings.ToLower(resource.ID), strings.ToLower(method.ID))
  76. outputfile := fmt.Sprintf(
  77. "../project/include/go/api_%s_%s_gen.go",
  78. strings.ToLower(resource.ID),
  79. strings.ToLower(method.ID),
  80. )
  81. if _, err := os.Stat(outputfile); os.IsNotExist(err) {
  82. file := G.NewFile(p.Package)
  83. file.Comment(method.Description)
  84. if o, err := json.MarshalIndent(method, "", " "); err == nil {
  85. file.Comment(string(o))
  86. }
  87. file.Func().Params(
  88. G.Id("t").Op("*").Id(ResourceStructId(resource)),
  89. ).Id(method.ID).Params(
  90. G.Id("ctx").Qual(IRIS_CTX, "Context"),
  91. ).Params(
  92. G.Id("resp").Interface(),
  93. G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  94. ).Block(G.Return())
  95. // if err = Write(path, file); err != nil {
  96. // return err
  97. // }
  98. return Write(outputfile, file)
  99. }
  100. return nil
  101. }
  102. func GenResources(p *Project) (err error) {
  103. var (
  104. file *G.File
  105. path string
  106. )
  107. if err = generateActionCommonFile(p); err != nil {
  108. return
  109. }
  110. for _, resource := range p.Resources {
  111. // Registra os campos retornados nos formatos do metodo list
  112. // FormatMap = map[string]string{}
  113. // Cria um novo arquivo para cada recurso
  114. file = G.NewFile(p.Package)
  115. InitFile(file, resource, p)
  116. // Inseri os comentarios de cada recurso no inicio do arquivo
  117. file.Comment(resource.Description).Line()
  118. // Define um tipo para registrar os metodos da api
  119. file.Type().Id(ResourceStructId(resource)).Struct().Line()
  120. for _, method := range resource.Methods {
  121. switch method.Template {
  122. case "", "implement":
  123. CreateDummy(p, resource, method)
  124. default:
  125. GenMethod(p, file, resource, method)
  126. }
  127. }
  128. // file.Var().DefsFunc(func(s *G.Group) {
  129. // values := G.Dict{}
  130. // for k, v := range FormatMap {
  131. // values[G.Lit(k)] = G.Lit(v)
  132. // }
  133. // s.Add(
  134. // G.Id("Format" + resource.Entity).Op("=").Map(G.String()).String().Values(values),
  135. // )
  136. // })
  137. file.Func().Params(
  138. G.Id("t").Op("*").Id(ResourceStructId((resource))),
  139. ).Id("Fields").Params(
  140. G.Id("filter").Op("*").Qual(API_URL, "Filter"),
  141. ).Params(
  142. G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  143. ).Block(
  144. G.Id(`
  145. if filter.Fields != nil {
  146. return
  147. }
  148. if filter.Format == "full" {
  149. filter.Fields = nil
  150. return
  151. }
  152. if fields, has := FormatSelection[`).Lit(fmt.Sprintf("%s.", resource.ID)).Id(`+filter.Format]; has {
  153. filter.Fields = api.MgoFields(fields)
  154. } else {
  155. err = errs.InvalidArgument().Details(&errs.Detail{
  156. Message: `).Qual("fmt", "Sprintf").Id(`("Invalid value for projection '%s'",filter.Format),
  157. })
  158. }
  159. return
  160. `),
  161. // G.If(
  162. // // G.List(G.Id("fields"), G.Id("has")).Op(":=").Id("FormatSelection"+resource.Entity).Index(G.Id("filter").Dot("Format")),
  163. // G.List(G.Id("fields"), G.Id("has")).Op(":=").Id("FormatSelection").Index(
  164. // G.Lit(resource.ID+".").Op("+").Id("filter").Dot("Format"),
  165. // ),
  166. // G.Id("has"),
  167. // ).Block(
  168. // G.Id("filter").Dot("Fields").Op("=").Id("api").Dot("MgoFields").Call(G.Id("fields")),
  169. // ).Else().Block(
  170. // G.Id("err").Op("=").Qual(API_URL, "Error").Call(
  171. // G.Qual(API_URL, "ERR_INVALID_PARAM_VALUE"),
  172. // G.Lit("Invalid value for %s"),
  173. // ),
  174. // // .Dot("Add").Call(
  175. // // G.Op("&").Qual(API_URL, "ErrDescription").Values(G.Dict{
  176. // // G.Id("Message"): G.Lit(""),
  177. // // }),
  178. // // ),
  179. // ),
  180. )
  181. // Fim do loop de methods
  182. // GenCall(f, resource)
  183. path = fmt.Sprintf("%s/%s/api_%s_gen.go", p.OutPath, p.Package, strings.ToLower(resource.ID))
  184. if err = Write(path, file); err != nil {
  185. return err
  186. }
  187. }
  188. // Fim do loop de recursos
  189. ResourceWG.Add(2)
  190. go GenIndexApi(p)
  191. ResourceWG.Wait()
  192. return nil
  193. }
  194. func GenQueries(p *Project, resourcesIdMap map[string]bool) {
  195. defer func() { ResourceWG.Done() }()
  196. if len(p.Queries.Queries) == 0 {
  197. return
  198. }
  199. file := G.NewFile(p.Package)
  200. queries := func(s *G.Statement) {
  201. var (
  202. query string
  203. found bool
  204. )
  205. for key, _ := range resourcesIdMap {
  206. if query, found = p.Queries.Queries[fmt.Sprintf("go.%s", key)]; !found {
  207. query = "{}"
  208. }
  209. s.Add(G.Qual(API_URL, "RegisterQuery(").Lit(key).Id(",").Lit(query).Id(")").Line())
  210. }
  211. }
  212. file.Id(`
  213. func init() {`).Do(queries).Id(`}`)
  214. if err := Write(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, "queries"), file); err != nil {
  215. panic(err)
  216. }
  217. }
  218. func GenIndexApi(p *Project) error {
  219. defer func() { ResourceWG.Done() }()
  220. var (
  221. stmt *G.Statement
  222. params string
  223. statments G.Statement
  224. idString string
  225. middlewares []string
  226. Index = G.NewFile(p.Package)
  227. RequestParams = G.Id(`RequestParams := `).Qual(CODE_GEN_V2_COMMON, "RequestParams")
  228. jwt = G.Id(`JWT := `).Qual(CODE_GEN_V2_AUTHORIZATION, "Handler")
  229. addJwt = false
  230. queryIndexsMap = map[string]bool{}
  231. callActionId = "apply"
  232. )
  233. statments = append(statments, G.Id(fmt.Sprintf("%s := ", callActionId)).Qual(API_URL, "CallAction"))
  234. statments = append(statments, RequestParams)
  235. // statments = append(statments)
  236. // Inicializa o mapa de filtros da api
  237. Index.Id(`
  238. import(
  239. // "reflect"
  240. // "runtime"
  241. // "strings"
  242. "fmt"
  243. )
  244. var (
  245. filtersApiReference = map[string]*`).Qual(CODE_GEN_V2_COMMON, "ApiFilter").Id(`{}
  246. FormatSelection = map[string]string{}
  247. Debug = api.NewDebug()
  248. )
  249. func init(){
  250. var (
  251. entity *common.ApiFilter
  252. files []`).Qual("os", "FileInfo").Id(`
  253. path = "./filters"
  254. err error
  255. )
  256. files, _ = `).Qual(CODE_GEN_V2_COMMON, "GetFiles").Id(`(path)
  257. for _, file := range files {
  258. if !file.IsDir() {
  259. entity = &common.ApiFilter{}
  260. if err = common.ParseJson(`).Qual("path/filepath", "Join").Id(`(path, file.Name()), entity); err != nil {
  261. panic(err)
  262. }
  263. filtersApiReference[entity.Id] = entity
  264. }
  265. }
  266. }
  267. type Action struct {
  268. Name string
  269. Fn func(context.Context) (interface{}, *`).Qual(API_ERROR, "Error").Id(`)
  270. }
  271. func executeAction(ctx context.Context, actions []Action) (resp interface{},err *errs.Error){
  272. var (
  273. stopPropagation bool
  274. // parts []string
  275. event *api.DebugEvent
  276. )
  277. debug, debugActive := ctx.Values().Get("#debug").(*api.DebugTaks);
  278. for _, action := range actions {
  279. if debugActive {
  280. fmt.Println("\texecuteAction -> ", action.Name)
  281. event = debug.Event("execute.action", action.Name)
  282. }
  283. resp, err = action.Fn(ctx)
  284. if debugActive {
  285. event.Data = resp
  286. event.Error = err
  287. }
  288. stopPropagation,_ = ctx.Values().GetBool("stop.propagation")
  289. switch {
  290. case stopPropagation, err != nil, resp != nil:
  291. return
  292. }
  293. }
  294. return
  295. }
  296. `)
  297. for rindex, resource := range p.Resources {
  298. stmt = G.Line().Id(resource.ID).Op(":=").Id(ResourceStructId(resource)).Values().Line()
  299. for k, method := range resource.Methods {
  300. // fmt.Println("----------------------------")
  301. args := []G.Code{
  302. G.Lit(method.HttpMethod),
  303. G.Lit(p.GetPath(method)),
  304. G.Line().Id("Debug.Handler()"),
  305. }
  306. middlewares = []string{}
  307. if len(method.ParametersString) > 0 {
  308. params = strings.Join(method.ParametersString, ",")
  309. // fmt.Println(fmt.Sprintf(`%s|RequestParams("%s", UserRequestParams)`, API_URL, params))
  310. stmt.Add(G.Line().Comment(
  311. "Lista de parametros a serem validados durante a requisição",
  312. ).Line().Id(fmt.Sprintf(`args%d%d := "%s"`, rindex, k, params)).Line())
  313. middlewares = append(middlewares, fmt.Sprintf(`RequestParams(args%d%d, UserRequestParams)`, rindex, k))
  314. }
  315. middlewares = append(middlewares, p.Middlewares...)
  316. middlewares = append(middlewares, method.Middlewares...)
  317. data := map[string]interface{}{
  318. "ResourceId": resource.ID,
  319. "MethodId": method.ID,
  320. }
  321. idString = fmt.Sprintf("%s:%s", resource.ID, method.ID)
  322. queryIndexsMap[idString] = true
  323. for _, m := range middlewares {
  324. if strings.Contains(m, "JWT") && !addJwt {
  325. addJwt = true
  326. RequestParams.Line().Add(jwt)
  327. }
  328. m = ResolveParams(m, data)
  329. parts := strings.Split(m, "|")
  330. // Quando parts possui tamanho maior que
  331. // significa que foi especificado um middleware de outro pacote.
  332. if len(parts) > 1 {
  333. args = append(args, G.Line().Id(callActionId).Call(
  334. G.Id(parts[1]),
  335. G.Qual(parts[0], parts[1]),
  336. ))
  337. } else {
  338. args = append(args, G.Line().Id(callActionId).Call(
  339. G.Lit(m),
  340. G.Id(m),
  341. ))
  342. }
  343. }
  344. args = append(args, G.Line().Id(callActionId).Call(
  345. G.Lit(fmt.Sprintf("%s.%s", resource.ID, method.ID)),
  346. G.Id(resource.ID).Dot(method.ID),
  347. ))
  348. if len(method.Postresponse) > 0 {
  349. args = append(args, G.Line().Id(method.Postresponse[0]))
  350. }
  351. stmt.Add(G.Line().Comment(method.Description).Line().Id("app").Dot("Handle").Call(args...).Line())
  352. }
  353. statments = append(statments, stmt)
  354. }
  355. // Cria a funcao que trata os filtros
  356. // statments = append(statments, G.Line().Comment("Filter request").Line().Id("app").Dot("Handle").Call(
  357. // G.Lit("GET"),
  358. // G.Lit(p.BasePath+"/filters/{id:string}"),
  359. // // G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(),
  360. // G.Id(fmt.Sprintf(`FilterHandle("../api/%s/filters")`, p.Package)),
  361. // ))
  362. // Cria a funcao que trata os metodos options
  363. statments = append(statments, G.Line().Comment("Options request").Line().Id("app").Dot("Options").Call(
  364. G.Lit("/{url:path}"),
  365. G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(
  366. G.Id(`ctx.ResponseWriter().Header().Set("Access-Control-Allow-Origin", ctx.GetHeader("Origin"))`),
  367. ),
  368. ))
  369. statments = append(statments, G.Line().Comment("Debug eventstream").Line().Id("app").Dot("Get").Call(
  370. G.Lit("/api/v1/debug"),
  371. G.Id(`apply("debug", Debug.EventStream())`),
  372. ))
  373. // Cria a funcao que registra as urls da api no arquivo api_index_gen.go
  374. Index.Func().Id("Register").Params(
  375. G.Id("app").Op("*").Qual(IRIS, "Application"),
  376. ).Block(
  377. statments...,
  378. ).Line()
  379. go GenQueries(p, queryIndexsMap)
  380. return Write(fmt.Sprintf("%s/%s/api_index_gen.go", p.OutPath, p.Package), Index)
  381. }
  382. func GenMethod(p *Project, f *G.File, r *Resource, method *Method) error {
  383. f.Comment(method.Description)
  384. if o, err := json.MarshalIndent(method, "", " "); err == nil {
  385. f.Comment(string(o))
  386. }
  387. stmt := f.Func().Params(
  388. // G.Id("t").Op("*").Id(strings.Title(r.ID)),
  389. G.Id("t").Op("*").Id(ResourceStructId(r)),
  390. ).Id(method.ID).Params(
  391. G.Id("ctx").Qual(IRIS_CTX, "Context"),
  392. // G.Id("resp").Op("*").Qual(API_URL, "ApiResponse"),
  393. ).Params(
  394. G.Id("resp").Interface(),
  395. G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  396. )
  397. generateActionsFiles(p, f, r, method)
  398. if middle, found := Middlewares[method.Template]; found {
  399. ctx := &MiddlewareContext{
  400. Project: p,
  401. Method: method,
  402. Middleware: middle,
  403. Statement: stmt,
  404. File: f,
  405. }
  406. return middle.Fn(ctx)
  407. }
  408. return fmt.Errorf("Method '%s' template not defined!", method.ID)
  409. }
  410. func generateActionCommonFile(p *Project) (err error) {
  411. path := fmt.Sprintf(
  412. "%s/include/go/actions/index_gen.go",
  413. CurrentDirectory,
  414. )
  415. if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  416. file := G.NewFile("actions")
  417. file.Id(`
  418. type Action struct {
  419. ID string
  420. }
  421. `).Line()
  422. err = Write(path, file)
  423. }
  424. return
  425. }
  426. func generateActionsFiles(p *Project, f *G.File, r *Resource, method *Method) {
  427. actions := []Action{}
  428. if method.Preconditions != nil {
  429. actions = append(actions, method.Preconditions...)
  430. }
  431. if method.BeforeResponse != nil {
  432. actions = append(actions, method.BeforeResponse...)
  433. }
  434. if method.BeforeParseRequest != nil {
  435. actions = append(actions, method.BeforeParseRequest...)
  436. }
  437. for _, action := range actions {
  438. path := fmt.Sprintf(
  439. "%s/include/go/actions/%s_gen.go",
  440. CurrentDirectory,
  441. action.ID,
  442. // method.Entity,
  443. // method.ID,
  444. // hookId,
  445. )
  446. if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  447. // methodId := fmt.Sprintf("%s%s%s", strings.Title(hookId), method.Entity, strings.Title(method.ID))
  448. file := G.NewFile("actions")
  449. context := map[string]interface{}{
  450. "imports": map[string]string{
  451. "errs": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs",
  452. "context": "github.com/kataras/iris/v12/context",
  453. },
  454. "function": strings.Title(action.ID),
  455. "hasContext": action.Context != nil,
  456. }
  457. spew.Dump(action.ID)
  458. spew.Dump(action.Context)
  459. out, _ := TemplateToString(hookStmtsTmpl, context)
  460. file.Id(out).Line()
  461. Write(path, file)
  462. }
  463. }
  464. // for hookId, _ := range method.Hooks {
  465. // // methodId := fmt.Sprintf("%s%s%s", strings.Title(hookId), method.Entity, strings.Title(method.ID))
  466. // path := fmt.Sprintf(
  467. // "%s/include/go/actions/%s_%s_%s_gen.go",
  468. // CurrentDirectory,
  469. // method.Entity,
  470. // method.ID,
  471. // hookId,
  472. // )
  473. // if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  474. // file := G.NewFile(p.Package)
  475. // context := map[string]interface{}{
  476. // "imports": map[string]string{
  477. // // "api": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api",
  478. // "errs": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs",
  479. // "context": "github.com/kataras/iris/v12/context",
  480. // },
  481. // }
  482. // out, _ := TemplateToString(hookStmtsTmpl, context)
  483. // file.Id(out).Line()
  484. // Write(path, file)
  485. // }
  486. // }
  487. }
  488. func GenFromGenericModel(p *Project, entity *EntityInfo) {
  489. var (
  490. posfix string
  491. propertie *G.Statement
  492. tproperties G.Statement
  493. // file = G.NewFile(p.Package)
  494. file = G.NewFile("models")
  495. cproperties = map[string]*G.Statement{}
  496. properties = G.Statement{}
  497. values = G.Dict{}
  498. model = p.GetSchema(entity.Name)
  499. entityName = entity.NewName
  500. // filename = "model_" + strings.ToLower(entityName)
  501. filename = "models/" + CamelToUnder(entityName)
  502. propName string
  503. )
  504. for _, meta := range model.Properties {
  505. propName = UpFirst(meta.ID)
  506. propertie = G.Id(propName)
  507. meta.FillTags(p, propName)
  508. posfix = ""
  509. // Registra a relaao entre as entidades
  510. if meta.Relation {
  511. posfix = "Ref"
  512. SR.Add(&Relation{
  513. Source: meta.GetType(),
  514. Target: model.ID,
  515. Attr: strings.Replace(meta.Tags["bson"], ",omitempty", "", 1),
  516. DB: model.DB,
  517. Collection: model.Collection,
  518. IsArray: meta.Array,
  519. })
  520. }
  521. if meta.Array {
  522. propertie.Index()
  523. }
  524. propertie.Id(entity.TranslateType(meta.Type) + posfix)
  525. // propertie.Id(meta.Type + posfix)
  526. // Adiciona as tags caso sejam definidas
  527. if meta.Tags != nil {
  528. propertie.Tag(meta.Tags)
  529. // if name, ok := meta.Tags["json"]; ok {
  530. // }
  531. }
  532. // Adiciona a crescricao como comentario
  533. if meta.Description != "" {
  534. propertie.Comment(meta.Description)
  535. }
  536. cproperties[meta.ID] = propertie
  537. if meta.ID == "ID" {
  538. values[G.Id("ID")] = G.Qual(BSON_PRIMITIVE, "NewObjectID").Call()
  539. }
  540. // Verifica se possui valor padrão
  541. if meta.Default != nil {
  542. values[G.Id(meta.ID)] = G.Lit(meta.Default)
  543. }
  544. properties = append(properties, propertie)
  545. }
  546. if model.Representations != nil {
  547. for posfix, rep := range model.Representations {
  548. tproperties = G.Statement{}
  549. for _, attr := range rep {
  550. tproperties = append(tproperties, cproperties[attr])
  551. }
  552. file.Comment(
  553. "Representação " + posfix,
  554. ).Line().Type().Id(
  555. model.ID + posfix,
  556. ).Struct(tproperties...)
  557. }
  558. }
  559. // Cria a entidade normal
  560. file.Line().Comment(model.Description).Line().Comment("Representação Completa")
  561. file.Type().Id(entityName).Struct(properties...)
  562. file.Comment(fmt.Sprintf("Cria uma instancia de %s.", entityName))
  563. // Cria a função de instanciar um novo elemento com os valores padrão determinados
  564. file.Func().Id("New" + entityName).Params().Op("*").Id(entityName).Block(
  565. G.Return(G.Op("&").Id(entityName).Values(values)),
  566. )
  567. // Salva o arquivo da entidade
  568. // if err := f.Save(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename)); err != nil {
  569. // fmt.Printf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename)
  570. if err := Write(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename), file); err != nil {
  571. panic(err)
  572. }
  573. }
  574. func Write(path string, file *G.File) error {
  575. // fmt.Println(fmt.Sprintf("Write -> %#v", path))
  576. return FilePutContents(path, fmt.Sprintf("%#v", file), 0777)
  577. }
  578. func ResourceStructId(resource *Resource) string {
  579. return strings.Title(resource.ID) + "Resource"
  580. }