schemas.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package tst
  2. import (
  3. "fmt"
  4. "strings"
  5. . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common" // . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/gen"
  6. TS "git.eugeniocarvalho.dev/eugeniucarvalho/gg/generators/typescript"
  7. )
  8. func GenSchemas(p *Project) error {
  9. var (
  10. attribName string
  11. propName string
  12. attribs []TS.CodeInterface
  13. attrib *TS.Group
  14. entityInfo *EntityInfo
  15. arrayProperties = []*Propertie{}
  16. )
  17. appendBasePatchClass()
  18. for _, entity := range p.Schemas {
  19. attribs = []TS.CodeInterface{}
  20. arrayProperties = []*Propertie{}
  21. entityInfo = p.ResponseEntity(entity.ID)
  22. for _, meta := range entity.Properties {
  23. propName = strings.Title(meta.ID)
  24. meta.FillTags(p, propName)
  25. // Registra a relaao entre as entidades
  26. // if meta.Relation {
  27. // SR.Add(&Relation{
  28. // Source: meta.GetType(),
  29. // Target: entity.ID,
  30. // Attr: strings.Replace(meta.Tags["bson"], ",omitempty", "", 1),
  31. // Collection: entity.Collection,
  32. // })
  33. // }
  34. if meta.Array {
  35. arrayProperties = append(arrayProperties, meta)
  36. }
  37. // Adiciona as tags caso sejam definidas
  38. if meta.Tags != nil {
  39. if name, ok := meta.Tags["json"]; ok {
  40. attribName = strings.Split(name, ",")[0]
  41. if attribName == "-" {
  42. attribName = meta.ID
  43. }
  44. }
  45. } else {
  46. attribName = meta.ID
  47. }
  48. if attribName == "id" {
  49. attribName = "_id"
  50. }
  51. meta.Name = attribName
  52. // Adiciona a crescricao como comentario
  53. attrib = &TS.Group{}
  54. if meta.Description != "" {
  55. // propertie.Comment(meta.Description)
  56. attrib.Comment(meta.Description)
  57. }
  58. if attribName != "" {
  59. optional := "?"
  60. // if getCustom(meta.Custom, "ts.optional").(bool) {
  61. // if !meta.Required {
  62. // options = "?"
  63. // }
  64. // attrib.Add(TS.Public().Id(attribName).Op(":").Id(TS.ConvType(meta.Type)))
  65. attrib.Add(TS.Id(attribName).Id(optional).Op(":").Id(TS.ConvType(meta.Type)))
  66. if meta.Array {
  67. attrib.Add(TS.Index())
  68. }
  69. attrib.Endl()
  70. attribs = append(attribs, attrib)
  71. }
  72. } // Fim do loop dos atributos
  73. // attribs = append(attribs, TS.Constructor(TS.Raw("opts: any")).Block(TS.Raw("opts && Object.assign(this,opts);")))
  74. unshift := []TS.CodeInterface{TS.Id(`constructor(entity?:any){ if(entity){Object.assign(this, entity);}}`)}
  75. attribs = append(unshift, attribs...)
  76. module.Line().Export().Class().Id(strings.Title(entity.ID)).Block(
  77. // module.Line().Export().Interface().Id(strings.Title(entity.ID)).Block(
  78. attribs...,
  79. ).Line()
  80. if !entityInfo.IsGeneric {
  81. createPathClass(entity, arrayProperties)
  82. }
  83. } // Fim do for de schema
  84. return nil
  85. }
  86. func createPathClass(entity *Entity, arrayProperties []*Propertie) {
  87. module.
  88. Line().
  89. Export().
  90. Class().
  91. Id(strings.Title(entity.ID + "Patch")).
  92. Extends().
  93. Id("BasePatch").
  94. BlockFun(func(g *TS.Group) {
  95. createClassProperties(g, entity, arrayProperties)
  96. createSetInitializeMethod(g, entity, arrayProperties)
  97. // createPatchMethod(g, entity, arrayProperties)
  98. createAddAndRemoveMethods(g, entity, arrayProperties)
  99. // g.Raw(`
  100. // protected emit(timeout = 0) {
  101. // super.emit(this.Patchs(), timeout);
  102. // }
  103. // `)
  104. }).
  105. Line()
  106. }
  107. func createClassProperties(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  108. for _, meta := range arrayProperties {
  109. g.Line().Add(
  110. TS.Raw(fmt.Sprintf("%s = new Map<string, { item: %s, action: string, type: string }>();", meta.ID, strings.Title(entity.ID))),
  111. )
  112. }
  113. }
  114. func createSetInitializeMethod(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  115. destructuring := []string{}
  116. for _, meta := range arrayProperties {
  117. destructuring = append(destructuring, fmt.Sprintf("%s=[]", meta.ID))
  118. }
  119. destructuringString := strings.Join(destructuring, ",")
  120. g.Add(TS.
  121. Line().
  122. Line().
  123. // Do().
  124. Constructor(TS.Raw(fmt.Sprintf("{%s} : %s", destructuringString, entity.ID))).
  125. BlockFun(func(block *TS.Group) {
  126. // block.Add(TS.Raw(`this.instance = instance;`).Line())
  127. block.Add(TS.Raw(`super();`).Line())
  128. // .Raw(`const {`)
  129. for _, meta := range arrayProperties {
  130. // block.Add(TS.Raw(fmt.Sprintf("if ($instance.%s) { this._set(this.%s, $instance.%s, '',-1);}", meta.ID, meta.ID, meta.ID)).Line())
  131. block.Add(TS.Raw(fmt.Sprintf("if (%s && %s.length) { this._set(this.%s, %s, '',-1);}", meta.ID, meta.ID, meta.ID, meta.ID)).Line())
  132. }
  133. }),
  134. )
  135. }
  136. func createPatchMethod(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  137. g.Add(TS.Line().
  138. Raw(`Patchs()`).
  139. BlockFun(func(block *TS.Group) {
  140. block.Add(TS.Raw(`const patchs = {`))
  141. for _, meta := range arrayProperties {
  142. block.Add(TS.
  143. Line().
  144. Raw(fmt.Sprintf("Add%s : [],", strings.Title(meta.ID))).
  145. Line().
  146. Raw(fmt.Sprintf("Remove%s : [],", strings.Title(meta.ID))).
  147. Line().
  148. Raw(fmt.Sprintf("Replace%s : [],", strings.Title(meta.ID))),
  149. )
  150. }
  151. block.
  152. Line().
  153. Raw(`};`).
  154. Line().
  155. Raw(`return patchs;`).
  156. Line()
  157. }),
  158. )
  159. }
  160. func createAddAndRemoveMethods(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  161. const timeout = 50
  162. for _, meta := range arrayProperties {
  163. g.Add(TS.
  164. Line().
  165. Id(fmt.Sprintf("Add%s", strings.Title(meta.ID))).
  166. Params(TS.Id("itens"), TS.Id(fmt.Sprintf("timeout = %d", timeout))).
  167. // Params(TS.Id("itens"), TS.Id("timeout")).
  168. Block(
  169. TS.Raw(fmt.Sprintf("this._set(this.%s, itens, 'add', timeout);return this;", meta.ID)),
  170. ).
  171. Line().
  172. Id(fmt.Sprintf("Remove%s", strings.Title(meta.ID))).
  173. Params(TS.Id("itens"), TS.Id(fmt.Sprintf("timeout = %d", timeout))).
  174. // Params(TS.Id("itens"), TS.Id("timeout")).
  175. Block(
  176. TS.Raw(fmt.Sprintf("this._set(this.%s, itens, 'remove', timeout);return this;", meta.ID)),
  177. ).
  178. Line().
  179. Id(fmt.Sprintf("Replace%s", strings.Title(meta.ID))).
  180. Params(TS.Id("itens"), TS.Id(fmt.Sprintf("timeout = %d", timeout))).
  181. Block(
  182. TS.Raw(fmt.Sprintf("this._set(this.%s, itens, 'replace', timeout);return this;", meta.ID)),
  183. ),
  184. )
  185. }
  186. }
  187. func appendBasePatchClass() {
  188. module.Line().Raw(`
  189. export class BasePatch {
  190. protected $set = {};
  191. protected $subscription: any;
  192. public locked = false;
  193. public change$ = new EventEmitter<any>();
  194. public $transformPatch = (patch) => patch;
  195. Set(options, timeout = 0) {
  196. this.$set = {...this.$set, ...options};
  197. if (timeout >= 0){
  198. this.emit(this.patch(), timeout);
  199. }
  200. }
  201. protected emit(patch:any , timeout = 0) {
  202. if (this.$subscription) { clearTimeout(this.$subscription); }
  203. this.locked = true;
  204. this.$subscription = setTimeout(() => this.change$.emit(patch), timeout);
  205. }
  206. protected __set(list, add, rem, replace) {
  207. list.forEach(element => {
  208. const {item} = element;
  209. switch (element.action) {
  210. case 'add': add.push(item); break;
  211. case 'replace': replace.push(item); break;
  212. case 'remove': if (element.type !== 'new') { rem.push(item._id || item); }
  213. }
  214. });
  215. }
  216. public from(patches, timeout = 50){
  217. const {$set = {}} = patches;
  218. this.Set($set, timeout);
  219. Object.keys(patches).map(prop => {
  220. if (prop.startsWith('$')) { return;}
  221. if (typeof this[prop] === 'function') {
  222. this[prop](patches[prop], timeout);
  223. }
  224. });
  225. }
  226. protected _set(_map: Map<string, any>, itens, action, timeout = 50) {
  227. (itens || []).map(item => {
  228. const id = (item._id || item);
  229. const has = _map.has(id)
  230. , el = _map.get(id);
  231. switch (action) {
  232. case 'replace':
  233. _map.set(id, {
  234. item,
  235. action: 'replace',
  236. type: 'new',
  237. });
  238. break;
  239. case 'add':
  240. if (!has) {
  241. _map.set(id, {
  242. item,
  243. action: 'add',
  244. type: 'new',
  245. });
  246. } else if (el.action === 'remove') {
  247. el.action = 'add';
  248. }
  249. break;
  250. case 'remove':
  251. if (has) {
  252. el.action = 'remove';
  253. break;
  254. }
  255. // tslint:disable-next-line:no-switch-case-fall-through
  256. default:
  257. _map.set(id, {
  258. item,
  259. action,
  260. type: '',
  261. });
  262. }
  263. });
  264. if (timeout >= 0){
  265. this.emit(this.patch(), timeout);
  266. }
  267. }
  268. patch() {
  269. const $this = this;
  270. const patchs = {};
  271. if (Object.getOwnPropertyNames(this.$set).length) {
  272. patchs['$set'] = this.$set;
  273. }
  274. Object.keys($this).map(prop => {
  275. if (prop.startsWith('$')) {
  276. return;
  277. }
  278. const adds = [],replace = [],remove = [];
  279. const captalized = prop[0].toUpperCase() + prop.slice(1);
  280. if ($this[prop].size) {
  281. this.__set($this[prop], adds, remove, replace);
  282. if (adds.length){ patchs[`).Raw("`Add${captalized}`").Raw(`] = adds; }
  283. if (replace.length){ patchs[`).Raw("`Replace${captalized}`").Raw(`] = replace; }
  284. if (remove.length){ patchs[`).Raw("`Remove${captalized}`").Raw(`] = remove; }
  285. }
  286. });
  287. return this.$transformPatch(patchs);
  288. }
  289. }
  290. `)
  291. }