store.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { Modes } from './../modes';
  2. export class Store {
  3. constructor() {
  4. this.store = {};
  5. this.nextStore = null;
  6. this.mode = Modes.RUN;
  7. }
  8. extendStore (nextStore) {
  9. this.nextStore = nextStore;
  10. }
  11. applyStore (id) {
  12. if(!this.store[id]) {
  13. if (this.nextStore !== null) {
  14. return this.nextStore.applyStore(id);
  15. } else {
  16. // TODO: better error message
  17. throw new Error(`Variable ${id} not found.`);
  18. }
  19. }
  20. const val = this.store[id];
  21. if (val.isRef) {
  22. return val.getRefObj();
  23. }
  24. return this.store[id];
  25. }
  26. updateStore (id, stoObj) {
  27. if(!this.store[id]) {
  28. if(this.nextStore !== null) {
  29. this.nextStore.updateStore(id, stoObj);
  30. return this;
  31. } else {
  32. // TODO: better error message
  33. throw new Error(`Variable ${id} not found.`);
  34. }
  35. } else {
  36. const oldObj = this.store[id];
  37. if(oldObj.readOnly) {
  38. // TODO: better error message
  39. throw new Error("Cannot change value of a read only variable: " + id);
  40. }
  41. if(oldObj.isRef) {
  42. oldObj.updateRef(stoObj);
  43. return this;
  44. } else if(oldObj.isCompatible(stoObj)) {
  45. stoObj.setID(id);
  46. this.store[id] = Object.freeze(stoObj);
  47. return this;
  48. } else {
  49. const oldType = oldObj.type;
  50. const stoType = stoObj.type;
  51. // TODO: better error message
  52. console.log(oldObj);
  53. console.log(stoObj);
  54. throw new Error(`${oldType} is not compatible with type ${stoType} given`);
  55. }
  56. }
  57. }
  58. //In case of future use of ref, it needs to have a special function to update the storeRefObject
  59. // and no the StoreObject refferenced by it
  60. // updateStoreRef(id, stoObjAddress) {...}
  61. insertStore (id, stoObj) {
  62. if (this.store[id]) {
  63. // TODO: better error message
  64. throw new Error(`${id} is already defined`);
  65. }
  66. stoObj.setID(id);
  67. this.store[id] = Object.freeze(stoObj);
  68. return this;
  69. }
  70. }