store.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. 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. throw new Error(`${oldType} is not compatible with type ${stoType} given`);
  53. }
  54. }
  55. }
  56. //In case of future use of ref, it needs to have a special function to update the storeRefObject
  57. // and no the StoreObject refferenced by it
  58. // updateStoreRef(id, stoObjAddress) {...}
  59. insertStore (id, stoObj) {
  60. if (this.store[id]) {
  61. // TODO: better error message
  62. throw new Error(`${id} is already defined`);
  63. }
  64. stoObj.setID(id);
  65. this.store[id] = Object.freeze(stoObj);
  66. return this;
  67. }
  68. }