store.js 1.9 KB

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