schemas.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. }
  274. // public Patchs() {
  275. // const patchs = {
  276. // AddMethods: [],
  277. // AddSamples: [],
  278. // AddCaracterizations: [],
  279. // RemoveMethods: [],
  280. // RemoveSamples: [],
  281. // RemoveCaracterizations: [],
  282. // $set: this.$set,
  283. // };
  284. // console.log('paths', this);
  285. // this.__set(this._samples, patchs.AddSamples, patchs.RemoveSamples);
  286. // this.__set(this._methods, patchs.AddMethods, patchs.RemoveMethods);
  287. // patchs.RemoveSamples.map(s => {
  288. // this.RemoveCaracterizations(this._form.caracterizations.filter(c => {
  289. // return c.sample === s.id;
  290. // }));
  291. // });
  292. // patchs.RemoveMethods.map(m => {
  293. // this.RemoveCaracterizations(this._form.caracterizations.filter(c => {
  294. // return c.method === m.id;
  295. // }));
  296. // });
  297. // this.__set(this._caracterizations, patchs.AddCaracterizations, patchs.RemoveCaracterizations);
  298. // return patchs;
  299. // }
  300. // public Patchs(patchs) {
  301. // const patchs = {
  302. // AddMethods: [],
  303. // AddSamples: [],
  304. // AddCaracterizations: [],
  305. // RemoveMethods: [],
  306. // RemoveSamples: [],
  307. // RemoveCaracterizations: [],
  308. // $set: this.$set,
  309. // };
  310. // console.log('paths', this);
  311. // this.__set(this._samples, patchs.AddSamples, patchs.RemoveSamples);
  312. // this.__set(this._methods, patchs.AddMethods, patchs.RemoveMethods);
  313. // patchs.RemoveSamples.map(s => {
  314. // this.RemoveCaracterizations(this._form.caracterizations.filter(c => {
  315. // return c.sample === s.id;
  316. // }));
  317. // });
  318. // patchs.RemoveMethods.map(m => {
  319. // this.RemoveCaracterizations(this._form.caracterizations.filter(c => {
  320. // return c.method === m.id;
  321. // }));
  322. // });
  323. // this.__set(this._caracterizations, patchs.AddCaracterizations, patchs.RemoveCaracterizations);
  324. // return patchs;
  325. // }
  326. // export class FormPatch {
  327. // $set = {};
  328. // _form: CaracterizationForm;
  329. // _samples = new Map<string, { item: Sample, action: string, type: string }>();
  330. // _methods = new Map<string, { item: CaracterizationMethod, action: string, type: string }>();
  331. // _caracterizations = new Map<string, { item: Caracterization, action: string, type: string }>();
  332. // setSolicitation(form: CaracterizationForm) {
  333. // // this._set(this._methods, form.methods.map(m => { return { id: m.id } }), '');
  334. // this._form = form;
  335. // this._set(this._samples, form.samples, '');
  336. // this._set(this._methods, form.methods, '');
  337. // this._set(this._caracterizations, form.caracterizations, '');
  338. // }
  339. // protected __set(list, add, rem) {
  340. // list.forEach((i) => {
  341. // switch (i.action) {
  342. // case 'add':
  343. // add.push(i.item);
  344. // break;
  345. // case 'remove':
  346. // (i.type !== 'new') && rem.push(i.item);
  347. // break;
  348. // }
  349. // });
  350. // }
  351. // public Patchs() {
  352. // const patchs = {
  353. // AddMethods: [],
  354. // AddSamples: [],
  355. // AddCaracterizations: [],
  356. // RemoveMethods: [],
  357. // RemoveSamples: [],
  358. // RemoveCaracterizations: [],
  359. // $set: this.$set,
  360. // };
  361. // console.log('paths', this);
  362. // this.__set(this._samples, patchs.AddSamples, patchs.RemoveSamples);
  363. // this.__set(this._methods, patchs.AddMethods, patchs.RemoveMethods);
  364. // patchs.RemoveSamples.map(s => {
  365. // this.RemoveCaracterizations(this._form.caracterizations.filter(c => {
  366. // return c.sample === s.id;
  367. // }));
  368. // });
  369. // patchs.RemoveMethods.map(m => {
  370. // this.RemoveCaracterizations(this._form.caracterizations.filter(c => {
  371. // return c.method === m.id;
  372. // }));
  373. // });
  374. // this.__set(this._caracterizations, patchs.AddCaracterizations, patchs.RemoveCaracterizations);
  375. // return patchs;
  376. // }
  377. // protected _set(_map: Map<string, any>, itens, action) {
  378. // (itens || []).map(item => {
  379. // const id = item.id || (item.method + item.sample);
  380. // const has = _map.has(id)
  381. // , el = _map.get(id);
  382. // switch (action) {
  383. // case 'add':
  384. // if (!has) {
  385. // _map.set(id, {
  386. // item: item,
  387. // action: 'add',
  388. // type: 'new',
  389. // });
  390. // } else if (el.action === 'remove') {
  391. // el.action = 'add';
  392. // }
  393. // break;
  394. // case 'remove':
  395. // if (has) {
  396. // el.action = 'remove';
  397. // }
  398. // break;
  399. // default:
  400. // _map.set(id, {
  401. // item: item,
  402. // action: '',
  403. // type: '',
  404. // });
  405. // }
  406. // });
  407. // }
  408. // AddMethods(itens) {
  409. // this._set(this._methods, itens, 'add');
  410. // }
  411. // AddSamples(itens) {
  412. // this._set(this._samples, itens, 'add');
  413. // }
  414. // AddCaracterizations(itens) {
  415. // this._set(this._caracterizations, itens, 'add');
  416. // }
  417. // RemoveMethods(itens) {
  418. // this._set(this._methods, itens, 'remove');
  419. // }
  420. // RemoveSamples(itens) {
  421. // this._set(this._samples, itens, 'remove');
  422. // }
  423. // RemoveCaracterizations(itens) {
  424. // this._set(this._caracterizations, itens, 'remove');
  425. // }
  426. // }