resources.go 19 KB

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