resources.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. )
  240. var (
  241. filtersApiReference = map[string]*`).Qual(CODE_GEN_V2_COMMON, "ApiFilter").Id(`{}
  242. FormatSelection = map[string]string{}
  243. )
  244. func init(){
  245. var (
  246. entity *common.ApiFilter
  247. files []`).Qual("os", "FileInfo").Id(`
  248. path = "./filters"
  249. err error
  250. )
  251. files, _ = `).Qual(CODE_GEN_V2_COMMON, "GetFiles").Id(`(path)
  252. for _, file := range files {
  253. if !file.IsDir() {
  254. entity = &common.ApiFilter{}
  255. if err = common.ParseJson(`).Qual("path/filepath", "Join").Id(`(path, file.Name()), entity); err != nil {
  256. panic(err)
  257. }
  258. filtersApiReference[entity.Id] = entity
  259. }
  260. }
  261. }
  262. func executeAction(ctx context.Context, actions ...func(context.Context) (interface{}, *`).Qual(API_ERROR, "Error").Id(`)) (resp interface{},err *errs.Error){
  263. var (
  264. stopPropagation bool
  265. debug = ctx.Values().Get("#debug");
  266. parts []string
  267. )
  268. for _, action := range actions {
  269. parts = strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
  270. event := debug.Event("execute.action", parts[len(parts)-1])
  271. resp, err = action(ctx)
  272. event.Data = iris.M{
  273. "resp": resp,
  274. "err": err,
  275. }
  276. stopPropagation,_ = ctx.Values().GetBool("stop.propagation")
  277. switch {
  278. case stopPropagation, err != nil, resp != nil:
  279. return
  280. }
  281. }
  282. return
  283. }
  284. `)
  285. for rindex, resource := range p.Resources {
  286. stmt = G.Line().Id(resource.ID).Op(":=").Id(ResourceStructId(resource)).Values().Line()
  287. for k, method := range resource.Methods {
  288. // fmt.Println("----------------------------")
  289. args := []G.Code{
  290. G.Lit(method.HttpMethod),
  291. G.Lit(p.GetPath(method)),
  292. }
  293. middlewares = []string{}
  294. if len(method.ParametersString) > 0 {
  295. params = strings.Join(method.ParametersString, ",")
  296. // fmt.Println(fmt.Sprintf(`%s|RequestParams("%s", UserRequestParams)`, API_URL, params))
  297. stmt.Add(G.Line().Comment(
  298. "Lista de parametros a serem validados durante a requisição",
  299. ).Line().Id(fmt.Sprintf(`args%d%d := "%s"`, rindex, k, params)).Line())
  300. middlewares = append(middlewares, fmt.Sprintf(`RequestParams(args%d%d, UserRequestParams)`, rindex, k))
  301. }
  302. middlewares = append(middlewares, p.Middlewares...)
  303. middlewares = append(middlewares, method.Middlewares...)
  304. data := map[string]interface{}{
  305. "ResourceId": resource.ID,
  306. "MethodId": method.ID,
  307. }
  308. idString = fmt.Sprintf("%s:%s", resource.ID, method.ID)
  309. queryIndexsMap[idString] = true
  310. for _, m := range middlewares {
  311. if strings.Contains(m, "JWT") && !addJwt {
  312. addJwt = true
  313. RequestParams.Line().Add(jwt)
  314. }
  315. m = ResolveParams(m, data)
  316. parts := strings.Split(m, "|")
  317. // Quando parts possui tamanho maior que
  318. // significa que foi especificado um middleware de outro pacote.
  319. if len(parts) > 1 {
  320. args = append(args, G.Line().Id(callActionId).Call(
  321. G.Id(parts[1]),
  322. G.Qual(parts[0], parts[1]),
  323. ))
  324. } else {
  325. args = append(args, G.Line().Id(callActionId).Call(
  326. G.Lit(m),
  327. G.Id(m),
  328. ))
  329. }
  330. }
  331. args = append(args, G.Line().Id(callActionId).Call(
  332. G.Lit(fmt.Sprintf("%s.%s", resource.ID, method.ID)),
  333. G.Id(resource.ID).Dot(method.ID),
  334. ))
  335. if len(method.Postresponse) > 0 {
  336. args = append(args, G.Line().Id(method.Postresponse[0]))
  337. }
  338. stmt.Add(G.Line().Comment(method.Description).Line().Id("app").Dot("Handle").Call(args...).Line())
  339. }
  340. statments = append(statments, stmt)
  341. }
  342. // Cria a funcao que trata os filtros
  343. // statments = append(statments, G.Line().Comment("Filter request").Line().Id("app").Dot("Handle").Call(
  344. // G.Lit("GET"),
  345. // G.Lit(p.BasePath+"/filters/{id:string}"),
  346. // // G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(),
  347. // G.Id(fmt.Sprintf(`FilterHandle("../api/%s/filters")`, p.Package)),
  348. // ))
  349. // Cria a funcao que trata os metodos options
  350. statments = append(statments, G.Line().Comment("Options request").Line().Id("app").Dot("Options").Call(
  351. G.Lit("/{url:path}"),
  352. G.Func().Params(G.Id("ctx").Qual(IRIS_CTX, "Context")).Block(
  353. G.Id(`ctx.ResponseWriter().Header().Set("Access-Control-Allow-Origin", ctx.GetHeader("Origin"))`),
  354. ),
  355. ))
  356. // Cria a funcao que registra as urls da api no arquivo api_index_gen.go
  357. Index.Func().Id("Register").Params(
  358. G.Id("app").Op("*").Qual(IRIS, "Application"),
  359. ).Block(
  360. statments...,
  361. ).Line()
  362. go GenQueries(p, queryIndexsMap)
  363. return Write(fmt.Sprintf("%s/%s/api_index_gen.go", p.OutPath, p.Package), Index)
  364. }
  365. func GenMethod(p *Project, f *G.File, r *Resource, method *Method) error {
  366. f.Comment(method.Description)
  367. if o, err := json.MarshalIndent(method, "", " "); err == nil {
  368. f.Comment(string(o))
  369. }
  370. stmt := f.Func().Params(
  371. // G.Id("t").Op("*").Id(strings.Title(r.ID)),
  372. G.Id("t").Op("*").Id(ResourceStructId(r)),
  373. ).Id(method.ID).Params(
  374. G.Id("ctx").Qual(IRIS_CTX, "Context"),
  375. // G.Id("resp").Op("*").Qual(API_URL, "ApiResponse"),
  376. ).Params(
  377. G.Id("resp").Interface(),
  378. G.Id("err").Op("*").Qual(API_ERROR, "Error"),
  379. )
  380. generateActionsFiles(p, f, r, method)
  381. if middle, found := Middlewares[method.Template]; found {
  382. ctx := &MiddlewareContext{
  383. Project: p,
  384. Method: method,
  385. Middleware: middle,
  386. Statement: stmt,
  387. File: f,
  388. }
  389. return middle.Fn(ctx)
  390. }
  391. return fmt.Errorf("Method '%s' template not defined!", method.ID)
  392. }
  393. func generateActionCommonFile(p *Project) (err error) {
  394. path := fmt.Sprintf(
  395. "%s/include/go/actions/index_gen.go",
  396. CurrentDirectory,
  397. )
  398. if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  399. file := G.NewFile("actions")
  400. file.Id(`
  401. type Action struct {
  402. ID string
  403. }
  404. `).Line()
  405. err = Write(path, file)
  406. }
  407. return
  408. }
  409. func generateActionsFiles(p *Project, f *G.File, r *Resource, method *Method) {
  410. actions := []Action{}
  411. if method.Preconditions != nil {
  412. actions = append(actions, method.Preconditions...)
  413. }
  414. if method.BeforeResponse != nil {
  415. actions = append(actions, method.BeforeResponse...)
  416. }
  417. if method.BeforeParseRequest != nil {
  418. actions = append(actions, method.BeforeParseRequest...)
  419. }
  420. for _, action := range actions {
  421. path := fmt.Sprintf(
  422. "%s/include/go/actions/%s_gen.go",
  423. CurrentDirectory,
  424. action.ID,
  425. // method.Entity,
  426. // method.ID,
  427. // hookId,
  428. )
  429. if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  430. // methodId := fmt.Sprintf("%s%s%s", strings.Title(hookId), method.Entity, strings.Title(method.ID))
  431. file := G.NewFile("actions")
  432. context := map[string]interface{}{
  433. "imports": map[string]string{
  434. "errs": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs",
  435. "context": "github.com/kataras/iris/v12/context",
  436. },
  437. "function": strings.Title(action.ID),
  438. "hasContext": action.Context != nil,
  439. }
  440. spew.Dump(action.ID)
  441. spew.Dump(action.Context)
  442. out, _ := TemplateToString(hookStmtsTmpl, context)
  443. file.Id(out).Line()
  444. Write(path, file)
  445. }
  446. }
  447. // for hookId, _ := range method.Hooks {
  448. // // methodId := fmt.Sprintf("%s%s%s", strings.Title(hookId), method.Entity, strings.Title(method.ID))
  449. // path := fmt.Sprintf(
  450. // "%s/include/go/actions/%s_%s_%s_gen.go",
  451. // CurrentDirectory,
  452. // method.Entity,
  453. // method.ID,
  454. // hookId,
  455. // )
  456. // if _, fileErr := os.Stat(path); os.IsNotExist(fileErr) {
  457. // file := G.NewFile(p.Package)
  458. // context := map[string]interface{}{
  459. // "imports": map[string]string{
  460. // // "api": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api",
  461. // "errs": "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs",
  462. // "context": "github.com/kataras/iris/v12/context",
  463. // },
  464. // }
  465. // out, _ := TemplateToString(hookStmtsTmpl, context)
  466. // file.Id(out).Line()
  467. // Write(path, file)
  468. // }
  469. // }
  470. }
  471. func GenFromGenericModel(p *Project, entity *EntityInfo) {
  472. var (
  473. posfix string
  474. propertie *G.Statement
  475. tproperties G.Statement
  476. // file = G.NewFile(p.Package)
  477. file = G.NewFile("models")
  478. cproperties = map[string]*G.Statement{}
  479. properties = G.Statement{}
  480. values = G.Dict{}
  481. model = p.GetSchema(entity.Name)
  482. entityName = entity.NewName
  483. // filename = "model_" + strings.ToLower(entityName)
  484. filename = "models/" + CamelToUnder(entityName)
  485. propName string
  486. )
  487. for _, meta := range model.Properties {
  488. propName = UpFirst(meta.ID)
  489. propertie = G.Id(propName)
  490. meta.FillTags(p, propName)
  491. posfix = ""
  492. // Registra a relaao entre as entidades
  493. if meta.Relation {
  494. posfix = "Ref"
  495. SR.Add(&Relation{
  496. Source: meta.GetType(),
  497. Target: model.ID,
  498. Attr: strings.Replace(meta.Tags["bson"], ",omitempty", "", 1),
  499. DB: model.DB,
  500. Collection: model.Collection,
  501. IsArray: meta.Array,
  502. })
  503. }
  504. if meta.Array {
  505. propertie.Index()
  506. }
  507. propertie.Id(entity.TranslateType(meta.Type) + posfix)
  508. // propertie.Id(meta.Type + posfix)
  509. // Adiciona as tags caso sejam definidas
  510. if meta.Tags != nil {
  511. propertie.Tag(meta.Tags)
  512. // if name, ok := meta.Tags["json"]; ok {
  513. // }
  514. }
  515. // Adiciona a crescricao como comentario
  516. if meta.Description != "" {
  517. propertie.Comment(meta.Description)
  518. }
  519. cproperties[meta.ID] = propertie
  520. if meta.ID == "ID" {
  521. values[G.Id("ID")] = G.Qual(BSON_PRIMITIVE, "NewObjectID").Call()
  522. }
  523. // Verifica se possui valor padrão
  524. if meta.Default != nil {
  525. values[G.Id(meta.ID)] = G.Lit(meta.Default)
  526. }
  527. properties = append(properties, propertie)
  528. }
  529. if model.Representations != nil {
  530. for posfix, rep := range model.Representations {
  531. tproperties = G.Statement{}
  532. for _, attr := range rep {
  533. tproperties = append(tproperties, cproperties[attr])
  534. }
  535. file.Comment(
  536. "Representação " + posfix,
  537. ).Line().Type().Id(
  538. model.ID + posfix,
  539. ).Struct(tproperties...)
  540. }
  541. }
  542. // Cria a entidade normal
  543. file.Line().Comment(model.Description).Line().Comment("Representação Completa")
  544. file.Type().Id(entityName).Struct(properties...)
  545. file.Comment(fmt.Sprintf("Cria uma instancia de %s.", entityName))
  546. // Cria a função de instanciar um novo elemento com os valores padrão determinados
  547. file.Func().Id("New" + entityName).Params().Op("*").Id(entityName).Block(
  548. G.Return(G.Op("&").Id(entityName).Values(values)),
  549. )
  550. // Salva o arquivo da entidade
  551. // if err := f.Save(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename)); err != nil {
  552. // fmt.Printf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename)
  553. if err := Write(fmt.Sprintf("%s/%s/%s_gen.go", p.OutPath, p.Package, filename), file); err != nil {
  554. panic(err)
  555. }
  556. }
  557. func Write(path string, file *G.File) error {
  558. // fmt.Println(fmt.Sprintf("Write -> %#v", path))
  559. return FilePutContents(path, fmt.Sprintf("%#v", file), 0777)
  560. }
  561. func ResourceStructId(resource *Resource) string {
  562. return strings.Title(resource.ID) + "Resource"
  563. }