schemas.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. optional := "?"
  63. // if getCustom(meta.Custom, "ts.optional").(bool) {
  64. // if !meta.Required {
  65. // options = "?"
  66. // }
  67. // attrib.Add(TS.Public().Id(attribName).Op(":").Id(TS.ConvType(meta.Type)))
  68. attrib.Add(TS.Id(attribName).Id(optional).Op(":").Id(TS.ConvType(meta.Type)))
  69. if meta.Array {
  70. attrib.Add(TS.Index())
  71. }
  72. attrib.Endl()
  73. attribs = append(attribs, attrib)
  74. }
  75. } // Fim do loop dos atributos
  76. // attribs = append(attribs, TS.Constructor(TS.Raw("opts: any")).Block(TS.Raw("opts && Object.assign(this,opts);")))
  77. unshift := []TS.CodeInterface{TS.Id(`constructor(entity?:any){ if(entity){Object.assign(this, entity);}}`)}
  78. attribs = append(unshift, attribs...)
  79. module.Line().Export().Class().Id(strings.Title(entity.ID)).Block(
  80. // module.Line().Export().Interface().Id(strings.Title(entity.ID)).Block(
  81. attribs...,
  82. ).Line()
  83. createPathClass(entity, arrayProperties)
  84. } // Fim do for de schema
  85. return nil
  86. }
  87. func createPathClass(entity *Entity, arrayProperties []*Propertie) {
  88. module.
  89. Line().
  90. Export().
  91. Class().
  92. Id(strings.Title(entity.ID + "Patch")).
  93. Extends().
  94. Id("BasePatch").
  95. BlockFun(func(g *TS.Group) {
  96. createClassProperties(g, entity, arrayProperties)
  97. createSetInitializeMethod(g, entity, arrayProperties)
  98. // createPatchMethod(g, entity, arrayProperties)
  99. createAddAndRemoveMethods(g, entity, arrayProperties)
  100. // g.Raw(`
  101. // protected emit(timeout = 0) {
  102. // super.emit(this.Patchs(), timeout);
  103. // }
  104. // `)
  105. }).
  106. Line()
  107. }
  108. func createClassProperties(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  109. for _, meta := range arrayProperties {
  110. g.Line().Add(
  111. TS.Raw(fmt.Sprintf("%s = new Map<string, { item: %s, action: string, type: string }>();", meta.ID, strings.Title(entity.ID))),
  112. )
  113. }
  114. }
  115. func createSetInitializeMethod(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  116. destructuring := []string{}
  117. for _, meta := range arrayProperties {
  118. destructuring = append(destructuring, fmt.Sprintf("%s=[]", meta.ID))
  119. }
  120. destructuringString := strings.Join(destructuring, ",")
  121. g.Add(TS.
  122. Line().
  123. Line().
  124. // Do().
  125. Constructor(TS.Raw(fmt.Sprintf("{%s} : %s", destructuringString, entity.ID))).
  126. BlockFun(func(block *TS.Group) {
  127. // block.Add(TS.Raw(`this.instance = instance;`).Line())
  128. block.Add(TS.Raw(`super();`).Line())
  129. // .Raw(`const {`)
  130. for _, meta := range arrayProperties {
  131. // block.Add(TS.Raw(fmt.Sprintf("if ($instance.%s) { this._set(this.%s, $instance.%s, '',-1);}", meta.ID, meta.ID, meta.ID)).Line())
  132. block.Add(TS.Raw(fmt.Sprintf("if (%s.length) { this._set(this.%s, %s, '',-1);}", meta.ID, meta.ID, meta.ID)).Line())
  133. }
  134. }),
  135. )
  136. }
  137. func createPatchMethod(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  138. g.Add(TS.Line().
  139. Raw(`Patchs()`).
  140. BlockFun(func(block *TS.Group) {
  141. block.Add(TS.Raw(`const patchs = {`))
  142. for _, meta := range arrayProperties {
  143. block.Add(TS.
  144. Line().
  145. Raw(fmt.Sprintf("Add%s : [],", strings.Title(meta.ID))).
  146. Line().
  147. Raw(fmt.Sprintf("Remove%s : [],", strings.Title(meta.ID))),
  148. )
  149. }
  150. block.
  151. Line().
  152. Raw(`};`).
  153. Line().
  154. Raw(`return patchs;`).
  155. Line()
  156. }),
  157. )
  158. }
  159. func createAddAndRemoveMethods(g *TS.Group, entity *Entity, arrayProperties []*Propertie) {
  160. const timeout = 50
  161. for _, meta := range arrayProperties {
  162. g.Add(TS.
  163. Line().
  164. Id(fmt.Sprintf("Add%s", strings.Title(meta.ID))).
  165. Params(TS.Id("itens"), TS.Id(fmt.Sprintf("timeout = %d", timeout))).
  166. // Params(TS.Id("itens"), TS.Id("timeout")).
  167. Block(
  168. TS.Raw(fmt.Sprintf("this._set(this.%s, itens, 'add', timeout);return this;", meta.ID)),
  169. ).
  170. Line().
  171. Id(fmt.Sprintf("Remove%s", strings.Title(meta.ID))).
  172. Params(TS.Id("itens"), TS.Id(fmt.Sprintf("timeout = %d", timeout))).
  173. // Params(TS.Id("itens"), TS.Id("timeout")).
  174. Block(
  175. TS.Raw(fmt.Sprintf("this._set(this.%s, itens, 'remove', timeout);return this;", meta.ID)),
  176. ),
  177. )
  178. }
  179. }
  180. func appendBasePatchClass() {
  181. module.Line().Raw(`
  182. export class BasePatch {
  183. protected $set = {};
  184. protected $subscription: any;
  185. public locked = false;
  186. public change$ = new EventEmitter<any>();
  187. public $transformPatch = (patch) => patch;
  188. Set(options, timeout = 0) {
  189. this.$set = {...this.$set, ...options};
  190. if (timeout >= 0){
  191. this.emit(this.patch(), timeout);
  192. }
  193. }
  194. protected emit(patch:any , timeout = 0) {
  195. if (this.$subscription) { clearTimeout(this.$subscription); }
  196. this.locked = true;
  197. this.$subscription = setTimeout(() => this.change$.emit(patch), timeout);
  198. }
  199. protected __set(list, add, rem) {
  200. list.forEach(element => {
  201. const item = element.item;
  202. switch (element.action) {
  203. case 'add':
  204. add.push(item);
  205. break;
  206. case 'remove':
  207. if (element.type !== 'new') { rem.push(item._id || item); }
  208. break;
  209. }
  210. });
  211. }
  212. public from(patches, timeout = 50){
  213. const {$set = {}} = patches;
  214. this.Set($set, timeout);
  215. Object.keys(patches).map(prop => {
  216. if (prop.startsWith('$')) { return;}
  217. if (typeof this[prop] === 'function') {
  218. this[prop](patches[prop], timeout);
  219. }
  220. });
  221. }
  222. protected _set(_map: Map<string, any>, itens, action, timeout = 50) {
  223. (itens || []).map(item => {
  224. const id = (item._id || item);
  225. const has = _map.has(id)
  226. , el = _map.get(id);
  227. switch (action) {
  228. case 'add':
  229. if (!has) {
  230. _map.set(id, {
  231. item: item,
  232. action: 'add',
  233. type: 'new',
  234. });
  235. } else if (el.action === 'remove') {
  236. el.action = 'add';
  237. }
  238. break;
  239. case 'remove':
  240. if (has) {
  241. el.action = 'remove';
  242. break;
  243. }
  244. // tslint:disable-next-line:no-switch-case-fall-through
  245. default:
  246. _map.set(id, {
  247. item,
  248. action,
  249. type: '',
  250. });
  251. }
  252. });
  253. if (timeout >= 0){
  254. this.emit(this.patch(), timeout);
  255. }
  256. }
  257. patch() {
  258. const $this = this;
  259. const patchs = {};
  260. if (Object.getOwnPropertyNames(this.$set).length) {
  261. patchs['$set'] = this.$set;
  262. }
  263. Object.keys($this).map(prop => {
  264. if (prop.startsWith('$')) {
  265. return;
  266. }
  267. const adds = [], remove = [];
  268. const captalized = prop[0].toUpperCase() + prop.slice(1);
  269. if ($this[prop].size) {
  270. this.__set($this[prop], adds, remove);
  271. if (adds.length){ patchs[`).Raw("`Add${captalized}`").Raw(`] = adds; }
  272. if (remove.length){ patchs[`).Raw("`Remove${captalized}`").Raw(`] = remove; }
  273. }
  274. });
  275. return this.$transformPatch(patchs);
  276. }
  277. }
  278. `)
  279. }