schemas.go 7.9 KB

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