store.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.isCompatible(stoObj)) {
  42. if(oldObj.isRef) {
  43. oldObj.updateRef(stoObj);
  44. return this;
  45. }
  46. stoObj.setID(id);
  47. this.store[id] = Object.freeze(stoObj);
  48. return this;
  49. } else {
  50. // TODO: better error message
  51. throw new Error(`${oldObj.type} is not compatible with the value given`);
  52. }
  53. }
  54. }
  55. //In case of future use of ref, it needs to have a special function to update the storeRefObject
  56. // and no the StoreObject refferenced by it
  57. // updateStoreRef(id, stoObjAddress) {...}
  58. insertStore (id, stoObj) {
  59. if (this.store[id]) {
  60. // TODO: better error message
  61. throw new Error(`${id} is already defined`);
  62. }
  63. stoObj.setID(id);
  64. this.store[id] = Object.freeze(stoObj);
  65. return this;
  66. }
  67. }