resources.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. // Cria a funcao que trata os metodos options
  353. statments = append(statments, G.Line().Comment("Options request").Line().Id("app").Dot("Options").Call(
  354. G.Lit("/{url:path}"),
  355. G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(
  356. G.Id(`ctx.ResponseWriter().Header().Set("Access-Control-Allow-Origin", ctx.GetHeader("Origin"))`),
  357. ),
  358. ))
  359. statments = append(statments, G.Line().Comment("Debug eventstream").Line().Id("app").Dot("Get").Call(
  360. G.Lit("/api/v1/debug"),
  361. G.Id(`apply("debug", Debug.EventStream())`),
  362. ))
  363. // Cria a funcao que registra as urls da api no arquivo api_index_gen.go
  364. Index.Func().Id("Register").Params(
  365. G.Id("app").Op("*").Qual(IRIS, "Application"),
  366. ).Block(
  367. statments...,
  368. ).Line()
  369. go GenQueries(p, queryIndexsMap)
  370. return Write(fmt.Sprintf("%s/%s/api_index_gen.go", p.OutPath, p.Package), Index)
  371. }
  372. func GenMethod(p *Project, f *G.File, r *Resource, method *Method) error {
  373. f.Comment(method.Description)
  374. if o, err := json.MarshalIndent(method, "", " "); err == nil {
  375. f.Comment(string(o))
  376. }
  377. stmt := f.Func().Params(
  378. // G.Id("t").Op("*").Id(strings.Title(r.ID)),
  379. G.Id("t").Op("*").Id(ResourceStructId(r)),
  380. ).Id(method.ID).Params(
  381. G.Id("ctx").Qual(IRIS_CTX, "Context"),
  382. // G.Id("resp").Op("*").Qual(API_URL, "ApiResponse"),
  383. ).Params(
  384. G.Id("resp").Interface(),
  385. G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  386. )
  387. generateActionsFiles(p, f, r, method)
  388. if middle, found := Middlewares[method.Template]; found {
  389. ctx := &MiddlewareContext{
  390. Project: p,
  391. Method: method,
  392. Middleware: middle,
  393. Statement: stmt,
  394. File: f,
  395. }
  396. return middle.Fn(ctx)
  397. }
  398. return fmt.Errorf("Method '%s' template not defined!", method.ID)
  399. }
  400. func generateActionCommonFile(p *Project) (err error) {
  401. path := fmt.Sprintf(
  402. "%s/include/go/actions/index_gen.go",
  403. CurrentDirectory,
  404. )
  405. if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  406. file := G.NewFile("actions")
  407. file.Id(`
  408. type Action struct {
  409. ID string
  410. }
  411. `).Line()
  412. err = Write(path, file)
  413. }
  414. return
  415. }
  416. func generateActionsFiles(p *Project, f *G.File, r *Resource, method *Method) {
  417. actions := []Action{}
  418. if method.Preconditions != nil {
  419. actions = append(actions, method.Preconditions...)
  420. }
  421. if method.BeforeResponse != nil {
  422. actions = append(actions, method.BeforeResponse...)
  423. }
  424. if method.BeforeParseRequest != nil {
  425. actions = append(actions, method.BeforeParseRequest...)
  426. }
  427. for _, action := range actions {
  428. path := fmt.Sprintf(
  429. "%s/include/go/actions/%s_gen.go",
  430. CurrentDirectory,
  431. action.ID,
  432. // method.Entity,
  433. // method.ID,
  434. // hookId,
  435. )
  436. if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  437. // methodId := fmt.Sprintf("%s%s%s", strings.Title(hookId), method.Entity, strings.Title(method.ID))
  438. file := G.NewFile("actions")
  439. context := map[string]interface{}{
  440. "imports": map[string]string{
  441. "errs": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs",
  442. "context": "github.com/kataras/iris/v12/context",
  443. },
  444. "function": strings.Title(action.ID),
  445. "hasContext": action.Context != nil,
  446. }
  447. spew.Dump(action.ID)
  448. spew.Dump(action.Context)
  449. out, _ := TemplateToString(hookStmtsTmpl, context)
  450. file.Id(out).Line()
  451. Write(path, file)
  452. }
  453. }
  454. // for hookId, _ := range method.Hooks {
  455. // // methodId := fmt.Sprintf("%s%s%s", strings.Title(hookId), method.Entity, strings.Title(method.ID))
  456. // path := fmt.Sprintf(
  457. // "%s/include/go/actions/%s_%s_%s_gen.go",
  458. // CurrentDirectory,
  459. // method.Entity,
  460. // method.ID,
  461. // hookId,
  462. // )
  463. // if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  464. // file := G.NewFile(p.Package)
  465. // context := map[string]interface{}{
  466. // "imports": map[string]string{
  467. // // "api": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api",
  468. // "errs": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs",
  469. // "context": "github.com/kataras/iris/v12/context",
  470. // },
  471. // }
  472. // out, _ := TemplateToString(hookStmtsTmpl, context)
  473. // file.Id(out).Line()
  474. // Write(path, file)
  475. // }
  476. // }
  477. }
  478. func GenFromGenericModel(p *Project, entity *EntityInfo) {
  479. var (
  480. posfix string
  481. propertie *G.Statement
  482. tproperties G.Statement
  483. // file = G.NewFile(p.Package)
  484. file = G.NewFile("models")
  485. cproperties = map[string]*G.Statement{}
  486. properties = G.Statement{}
  487. values = G.Dict{}
  488. model = p.GetSchema(entity.Name)
  489. entityName = entity.NewName
  490. // filename = "model_" + strings.ToLower(entityName)
  491. filename = "models/" + CamelToUnder(entityName)
  492. propName string
  493. )
  494. for _, meta := range model.Properties {
  495. propName = UpFirst(meta.ID)
  496. propertie = G.Id(propName)
  497. meta.FillTags(p, propName)
  498. posfix = ""
  499. // Registra a relaao entre as entidades
  500. if meta.Relation {
  501. posfix = "Ref"
  502. SR.Add(&Relation{
  503. Source: meta.GetType(),
  504. Target: model.ID,
  505. Attr: strings.Replace(meta.Tags["bson"], ",omitempty", "", 1),
  506. DB: model.DB,
  507. Collection: model.Collection,
  508. IsArray: meta.Array,
  509. })
  510. }
  511. if meta.Array {
  512. propertie.Index()
  513. }
  514. propertie.Id(entity.TranslateType(meta.Type) + posfix)
  515. // propertie.Id(meta.Type + posfix)
  516. // Adiciona as tags caso sejam definidas
  517. if meta.Tags != nil {
  518. propertie.Tag(meta.Tags)
  519. // if name, ok := meta.Tags["json"]; ok {
  520. // }
  521. }
  522. // Adiciona a crescricao como comentario
  523. if meta.Description != "" {
  524. propertie.Comment(meta.Description)
  525. }
  526. cproperties[meta.ID] = propertie
  527. if meta.ID == "ID" {
  528. values[G.Id("ID")] = G.Qual(BSON_PRIMITIVE, "NewObjectID").Call()
  529. }
  530. // Verifica se possui valor padrão
  531. if meta.Default != nil {
  532. values[G.Id(meta.ID)] = G.Lit(meta.Default)
  533. }
  534. properties = append(properties, propertie)
  535. }
  536. if model.Representations != nil {
  537. for posfix, rep := range model.Representations {
  538. tproperties = G.Statement{}
  539. for _, attr := range rep {
  540. tproperties = append(tproperties, cproperties[attr])
  541. }
  542. file.Comment(
  543. "Representação " + posfix,
  544. ).Line().Type().Id(
  545. model.ID + posfix,
  546. ).Struct(tproperties...)
  547. }
  548. }
  549. // Cria a entidade normal
  550. file.Line().Comment(model.Description).Line().Comment("Representação Completa")
  551. file.Type().Id(entityName).Struct(properties...)
  552. file.Comment(fmt.Sprintf("Cria uma instancia de %s.", entityName))
  553. // Cria a função de instanciar um novo elemento com os valores padrão determinados
  554. file.Func().Id("New" + entityName).Params().Op("*").Id(entityName).Block(
  555. G.Return(G.Op("&").Id(entityName).Values(values)),
  556. )
  557. // Salva o arquivo da entidade
  558. // if err := f.Save(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename)); err != nil {
  559. // fmt.Printf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename)
  560. if err := Write(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename), file); err != nil {
  561. panic(err)
  562. }
  563. }
  564. func Write(path string, file *G.File) error {
  565. // fmt.Println(fmt.Sprintf("Write -> %#v", path))
  566. return FilePutContents(path, fmt.Sprintf("%#v", file), 0777)
  567. }
  568. func ResourceStructId(resource *Resource) string {
  569. return strings.Title(resource.ID) + "Resource"
  570. }