OneToOne.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. const express = require('express');
  2. const path = require('path');
  3. const RepositorySystem = require('../systems/RepositorySystem');
  4. const Actions = require('../systems/ActionSystem');
  5. class OneToOne {
  6. constructor(name, inceptor){
  7. this.name = name;
  8. this.scheme = {
  9. auto_increment: 1,
  10. fields: [
  11. {
  12. key: "name",
  13. type: "string",
  14. keyLength: 200
  15. }
  16. ]
  17. };
  18. this.repository = RepositorySystem.create(this.name, this.scheme);
  19. this.inceptor = inceptor;
  20. this.inceptorScheme = {
  21. fields: [
  22. {
  23. key: this.name + "_id",
  24. type: "integer",
  25. fk: {
  26. "table": this.name,
  27. "key": "id"
  28. }
  29. }
  30. ]
  31. };
  32. this.inceptorRepo = RepositorySystem.create(this.inceptor, this.inceptorScheme);
  33. this._init2();
  34. }
  35. _init2() {
  36. Actions.on('model'+this.inceptor, (model) => {
  37. return this.repository.getPage(0,1000)
  38. .then((categories) => {
  39. return {
  40. ...model,
  41. [this.name]: {
  42. Filter: {
  43. type: "onetoone",
  44. options: categories.reduce((data,a) => {return {...data, [a.id]: a.name }}, {}),
  45. name: this.name,
  46. field: this.name + "_id",
  47. order: 50
  48. }
  49. }
  50. }
  51. })
  52. });
  53. Actions.on('get'+this.inceptor, (product) => {
  54. if (!product[this.name + "_id"]) return product;
  55. return this.repository.raw().where('id', product[this.name+"_id"])
  56. .then((items) => {
  57. product[this.name] = items[0];
  58. delete product[this.name+"_id"];
  59. return product;
  60. });
  61. });
  62. Actions.on('import'+this.inceptor, (dataset) => {
  63. return this.repository.getPage(0,1000).then((cats) => {
  64. let catNames = cats.reduce((w, a) => {
  65. w[a.name] = a.id;
  66. return w;
  67. },{});
  68. let categories = dataset.reduce((acc, item) => {
  69. let categories = (item[this.name] || '');
  70. if(categories && !acc.includes(categories))acc.push(categories);
  71. return acc;
  72. },[]);
  73. var filtered = categories.filter(function(value, index, arr){
  74. return !catNames[value];
  75. });
  76. filtered = filtered.map((name) => {return {name}})
  77. return this.repository.batchInsert(filtered)
  78. .then(() => this.repository.getPage(0,1000))
  79. .then((cats) => {
  80. return cats.reduce((w, a) => {
  81. w[a.name] = a.id;
  82. return w;
  83. },{});
  84. })
  85. .then((names) => dataset.map((item) => {
  86. let categories = item[this.name];
  87. if(categories)item[this.name + "_id"] = names[categories];
  88. return item;
  89. }));
  90. });
  91. });
  92. }
  93. }
  94. module.exports = OneToOne;