OneToMany.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const express = require('express');
  2. const path = require('path');
  3. const RepositorySystem = require('../systems/RepositorySystem');
  4. const Actions = require('../systems/ActionSystem');
  5. class OneToMany {
  6. constructor(name, inceptor){
  7. this.name = name;
  8. this.scheme = {
  9. auto_increment: 1,
  10. fields: [
  11. {
  12. key: "name",
  13. type: "text",
  14. keyLength: 200
  15. },
  16. {
  17. key: inceptor + "_id",
  18. type: "integer",
  19. fk: {
  20. "table": this.inceptor,
  21. "key": "id"
  22. }
  23. }
  24. ]
  25. };
  26. this.repository = RepositorySystem.create(this.name, this.scheme);
  27. this.inceptor = inceptor;
  28. this.inceptorScheme = {
  29. fields: [
  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: "onetomany",
  44. options: categories.reduce((data,a) => {return {...data, [a.id]: a.name }}, {}),
  45. name: this.name,
  46. field: this.name,
  47. }
  48. }
  49. }
  50. })
  51. });
  52. Actions.on('get'+this.inceptor, (product) => {
  53. if(!product.id) return product;
  54. return this.repository.raw().where(this.inceptor + '_id', product.id)
  55. .then((categories) => {
  56. product[this.name] = categories;
  57. return product;
  58. });
  59. });
  60. Actions.on('post' + this.name, (address, req, res) => {
  61. if(!req.user) {
  62. res.sendStatus(401);
  63. throw new Error("No user on req object");
  64. }
  65. console.log("ADDRESS")
  66. console.log(address)
  67. address[this.inceptor + "_id"] = req.user.id;
  68. return address;
  69. });
  70. console.log(Actions);
  71. }
  72. }
  73. module.exports = OneToMany;