resources.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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_bson_%d_ *", resource.Entity, now)).Qual(BSON, "M"),
  52. G.Id(fmt.Sprintf("_%s_error_%d_ *", resource.Entity, now)).Qual(API_ERROR, "Error"),
  53. G.Id(fmt.Sprintf("_%s_sync_%d_ *", resource.Entity, now)).Qual("sync", "WaitGroup"),
  54. G.Id(fmt.Sprintf("_%s_primitive_%d_ *", resource.Entity, now)).Qual("go.mongodb.org/mongo-driver/bson/primitive", "ObjectID"),
  55. G.Id(fmt.Sprintf("_%s_models_%d_ *", resource.Entity, now)).Qual(
  56. fmt.Sprintf("%s/build/%s/models", p.Custom["go.package.repository"].(string), p.Package),
  57. "Entity",
  58. ),
  59. G.Id(fmt.Sprintf("_%s_actions_%d_ *", resource.Entity, now)).Qual(
  60. fmt.Sprintf("%s/build/%s/actions", p.Custom["go.package.repository"].(string), p.Package),
  61. "Action",
  62. ),
  63. )
  64. file.Func().Id("init").Params().BlockFunc(func(s *G.Group) {
  65. for _, v := range resource.Formats {
  66. s.Add(G.Id("FormatSelection").Index(G.Lit(resource.ID + "." + v.Id)).Op("=").Lit(v.Fields))
  67. }
  68. })
  69. }
  70. func CreateDummy(p *Project, resource *Resource, method *Method) error {
  71. // Verifica se existe um arquivo na pasta de include.
  72. // Caso o arquivo não exista um novo arquivo é criado.
  73. // outputfile := fmt.Sprintf("%s/include/go/api_%s_%s.go", CurrentDirectory, strings.ToLower(resource.ID), strings.ToLower(method.ID))
  74. outputfile := fmt.Sprintf(
  75. "../project/include/go/api_%s_%s_gen.go",
  76. strings.ToLower(resource.ID),
  77. strings.ToLower(method.ID),
  78. )
  79. if _, err := os.Stat(outputfile); os.IsNotExist(err) {
  80. file := G.NewFile(p.Package)
  81. file.Comment(method.Description)
  82. if o, err := json.MarshalIndent(method, "", " "); err == nil {
  83. file.Comment(string(o))
  84. }
  85. file.Func().Params(
  86. G.Id("t").Op("*").Id(ResourceStructId(resource)),
  87. ).Id(method.ID).Params(
  88. G.Id("ctx").Qual(IRIS_CTX, "Context"),
  89. ).Params(
  90. G.Id("resp").Interface(),
  91. G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  92. ).Block(G.Return())
  93. // if err = Write(path, file); err != nil {
  94. // return err
  95. // }
  96. return Write(outputfile, file)
  97. }
  98. return nil
  99. }
  100. func GenResources(p *Project) (err error) {
  101. var (
  102. file *G.File
  103. path string
  104. )
  105. if err = generateActionCommonFile(p); err != nil {
  106. return
  107. }
  108. for _, resource := range p.Resources {
  109. // Registra os campos retornados nos formatos do metodo list
  110. // FormatMap = map[string]string{}
  111. // Cria um novo arquivo para cada recurso
  112. file = G.NewFile(p.Package)
  113. InitFile(file, resource, p)
  114. // Inseri os comentarios de cada recurso no inicio do arquivo
  115. file.Comment(resource.Description).Line()
  116. // Define um tipo para registrar os metodos da api
  117. file.Type().Id(ResourceStructId(resource)).Struct().Line()
  118. for _, method := range resource.Methods {
  119. switch method.Template {
  120. case "", "implement":
  121. CreateDummy(p, resource, method)
  122. default:
  123. GenMethod(p, file, resource, method)
  124. }
  125. }
  126. // file.Var().DefsFunc(func(s *G.Group) {
  127. // values := G.Dict{}
  128. // for k, v := range FormatMap {
  129. // values[G.Lit(k)] = G.Lit(v)
  130. // }
  131. // s.Add(
  132. // G.Id("Format" + resource.Entity).Op("=").Map(G.String()).String().Values(values),
  133. // )
  134. // })
  135. file.Func().Params(
  136. G.Id("t").Op("*").Id(ResourceStructId((resource))),
  137. ).Id("Fields").Params(
  138. G.Id("filter").Op("*").Qual(API_URL, "Filter"),
  139. ).Params(
  140. G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  141. ).Block(
  142. G.Id(`
  143. if filter.Fields != nil {
  144. return
  145. }
  146. if filter.Format == "full" {
  147. filter.Fields = nil
  148. return
  149. }
  150. if fields, has := FormatSelection[`).Lit(fmt.Sprintf("%s.", resource.ID)).Id(`+filter.Format]; has {
  151. filter.Fields = api.MgoFields(fields)
  152. } else {
  153. err = errs.InvalidArgument().Details(&errs.Detail{
  154. Message: `).Qual("fmt", "Sprintf").Id(`("Invalid value for projection '%s'",filter.Format),
  155. })
  156. }
  157. return
  158. `),
  159. // G.If(
  160. // // G.List(G.Id("fields"), G.Id("has")).Op(":=").Id("FormatSelection"+resource.Entity).Index(G.Id("filter").Dot("Format")),
  161. // G.List(G.Id("fields"), G.Id("has")).Op(":=").Id("FormatSelection").Index(
  162. // G.Lit(resource.ID+".").Op("+").Id("filter").Dot("Format"),
  163. // ),
  164. // G.Id("has"),
  165. // ).Block(
  166. // G.Id("filter").Dot("Fields").Op("=").Id("api").Dot("MgoFields").Call(G.Id("fields")),
  167. // ).Else().Block(
  168. // G.Id("err").Op("=").Qual(API_URL, "Error").Call(
  169. // G.Qual(API_URL, "ERR_INVALID_PARAM_VALUE"),
  170. // G.Lit("Invalid value for %s"),
  171. // ),
  172. // // .Dot("Add").Call(
  173. // // G.Op("&").Qual(API_URL, "ErrDescription").Values(G.Dict{
  174. // // G.Id("Message"): G.Lit(""),
  175. // // }),
  176. // // ),
  177. // ),
  178. )
  179. // Fim do loop de methods
  180. // GenCall(f, resource)
  181. path = fmt.Sprintf("%s/%s/api_%s_gen.go", p.OutPath, p.Package, strings.ToLower(resource.ID))
  182. if err = Write(path, file); err != nil {
  183. return err
  184. }
  185. }
  186. // Fim do loop de recursos
  187. ResourceWG.Add(2)
  188. go GenIndexApi(p)
  189. ResourceWG.Wait()
  190. return nil
  191. }
  192. func GenQueries(p *Project, resourcesIdMap map[string]bool) {
  193. defer func() { ResourceWG.Done() }()
  194. if len(p.Queries.Queries) == 0 {
  195. return
  196. }
  197. file := G.NewFile(p.Package)
  198. queries := func(s *G.Statement) {
  199. var (
  200. query string
  201. found bool
  202. )
  203. for key, _ := range resourcesIdMap {
  204. if query, found = p.Queries.Queries[fmt.Sprintf("go.%s", key)]; !found {
  205. query = "{}"
  206. }
  207. s.Add(G.Qual(API_URL, "RegisterQuery(").Lit(key).Id(",").Lit(query).Id(")").Line())
  208. }
  209. }
  210. file.Id(`
  211. func init() {`).Do(queries).Id(`}`)
  212. if err := Write(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, "queries"), file); err != nil {
  213. panic(err)
  214. }
  215. }
  216. func GenIndexApi(p *Project) error {
  217. defer func() { ResourceWG.Done() }()
  218. var (
  219. stmt *G.Statement
  220. params string
  221. statments G.Statement
  222. idString string
  223. middlewares []string
  224. Index = G.NewFile(p.Package)
  225. RequestParams = G.Id(`RequestParams := `).Qual(CODE_GEN_V2_COMMON, "RequestParams")
  226. jwt = G.Id(`JWT := `).Qual(CODE_GEN_V2_AUTHORIZATION, "Handler")
  227. addJwt = false
  228. queryIndexsMap = map[string]bool{}
  229. callActionId = "apply"
  230. )
  231. statments = append(statments, G.Id(fmt.Sprintf("%s := ", callActionId)).Qual(API_URL, "CallAction"))
  232. statments = append(statments, RequestParams)
  233. // statments = append(statments)
  234. // Inicializa o mapa de filtros da api
  235. Index.Id(`
  236. import(
  237. "reflect"
  238. "runtime"
  239. "strings"
  240. )
  241. var (
  242. filtersApiReference = map[string]*`).Qual(CODE_GEN_V2_COMMON, "ApiFilter").Id(`{}
  243. FormatSelection = map[string]string{}
  244. Debug = api.NewDebug()
  245. )
  246. func init(){
  247. var (
  248. entity *common.ApiFilter
  249. files []`).Qual("os", "FileInfo").Id(`
  250. path = "./filters"
  251. err error
  252. )
  253. files, _ = `).Qual(CODE_GEN_V2_COMMON, "GetFiles").Id(`(path)
  254. for _, file := range files {
  255. if !file.IsDir() {
  256. entity = &common.ApiFilter{}
  257. if err = common.ParseJson(`).Qual("path/filepath", "Join").Id(`(path, file.Name()), entity); err != nil {
  258. panic(err)
  259. }
  260. filtersApiReference[entity.Id] = entity
  261. }
  262. }
  263. }
  264. func executeAction(ctx context.Context, actions ...func(context.Context) (interface{}, *`).Qual(API_ERROR, "Error").Id(`)) (resp interface{},err *errs.Error){
  265. var (
  266. stopPropagation bool
  267. parts []string
  268. )
  269. debug, debugActive := ctx.Values().Get("#debug").(*api.DebugTaks);
  270. for _, action := range actions {
  271. resp, err = action(ctx)
  272. if debugActive {
  273. parts = strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
  274. event := debug.Event("execute.action", parts[len(parts)-1])
  275. event.Data = resp
  276. event.Error = err
  277. }
  278. stopPropagation,_ = ctx.Values().GetBool("stop.propagation")
  279. switch {
  280. case stopPropagation, err != nil, resp != nil:
  281. return
  282. }
  283. }
  284. return
  285. }
  286. `)
  287. for rindex, resource := range p.Resources {
  288. stmt = G.Line().Id(resource.ID).Op(":=").Id(ResourceStructId(resource)).Values().Line()
  289. for k, method := range resource.Methods {
  290. // fmt.Println("----------------------------")
  291. args := []G.Code{
  292. G.Lit(method.HttpMethod),
  293. G.Lit(p.GetPath(method)),
  294. G.Line().Id("Debug.Handler()"),
  295. }
  296. middlewares = []string{}
  297. if len(method.ParametersString) > 0 {
  298. params = strings.Join(method.ParametersString, ",")
  299. // fmt.Println(fmt.Sprintf(`%s|RequestParams("%s", UserRequestParams)`, API_URL, params))
  300. stmt.Add(G.Line().Comment(
  301. "Lista de parametros a serem validados durante a requisição",
  302. ).Line().Id(fmt.Sprintf(`args%d%d := "%s"`, rindex, k, params)).Line())
  303. middlewares = append(middlewares, fmt.Sprintf(`RequestParams(args%d%d, UserRequestParams)`, rindex, k))
  304. }
  305. middlewares = append(middlewares, p.Middlewares...)
  306. middlewares = append(middlewares, method.Middlewares...)
  307. data := map[string]interface{}{
  308. "ResourceId": resource.ID,
  309. "MethodId": method.ID,
  310. }
  311. idString = fmt.Sprintf("%s:%s", resource.ID, method.ID)
  312. queryIndexsMap[idString] = true
  313. for _, m := range middlewares {
  314. if strings.Contains(m, "JWT") && !addJwt {
  315. addJwt = true
  316. RequestParams.Line().Add(jwt)
  317. }
  318. m = ResolveParams(m, data)
  319. parts := strings.Split(m, "|")
  320. // Quando parts possui tamanho maior que
  321. // significa que foi especificado um middleware de outro pacote.
  322. if len(parts) > 1 {
  323. args = append(args, G.Line().Id(callActionId).Call(
  324. G.Id(parts[1]),
  325. G.Qual(parts[0], parts[1]),
  326. ))
  327. } else {
  328. args = append(args, G.Line().Id(callActionId).Call(
  329. G.Lit(m),
  330. G.Id(m),
  331. ))
  332. }
  333. }
  334. args = append(args, G.Line().Id(callActionId).Call(
  335. G.Lit(fmt.Sprintf("%s.%s", resource.ID, method.ID)),
  336. G.Id(resource.ID).Dot(method.ID),
  337. ))
  338. if len(method.Postresponse) > 0 {
  339. args = append(args, G.Line().Id(method.Postresponse[0]))
  340. }
  341. stmt.Add(G.Line().Comment(method.Description).Line().Id("app").Dot("Handle").Call(args...).Line())
  342. }
  343. statments = append(statments, stmt)
  344. }
  345. // Cria a funcao que trata os filtros
  346. // statments = append(statments, G.Line().Comment("Filter request").Line().Id("app").Dot("Handle").Call(
  347. // G.Lit("GET"),
  348. // G.Lit(p.BasePath+"/filters/{id:string}"),
  349. // // G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(),
  350. // G.Id(fmt.Sprintf(`FilterHandle("../api/%s/filters")`, p.Package)),
  351. // ))
  352. statments = append(statments, G.Line().Comment("Debug eventstream").Line().Id("app").Dot("Get").Call(
  353. G.Lit("/debug"),
  354. G.Id(`apply("debug", Debug.EventStream())`),
  355. // G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(
  356. // G.Id(`
  357. // if err = asyncTaskManagerService.Hub.UpgradeConnection(
  358. // ctx,
  359. // fmt.Sprintf("async.task.%s", asyncTaskId),
  360. // ); err != nil {
  361. // ctx.
  362. // }
  363. // `),
  364. // ),
  365. ))
  366. // Cria a funcao que trata os metodos options
  367. statments = append(statments, G.Line().Comment("Options request").Line().Id("app").Dot("Options").Call(
  368. G.Lit("/{url:path}"),
  369. G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(
  370. G.Id(`ctx.ResponseWriter().Header().Set("Access-Control-Allow-Origin", ctx.GetHeader("Origin"))`),
  371. ),
  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. }