store.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.extendStore !== null) {
  29. return this.extendStore.updateStore(id, stoObj);
  30. } else {
  31. // TODO: better error message
  32. throw new Error(`Variable ${id} not found.`);
  33. }
  34. } else {
  35. const oldObj = this.store[id];
  36. if(oldObj.readOnly) {
  37. // TODO: better error message
  38. throw new Error("Cannot change value of a read only variable: " + id);
  39. }
  40. if(oldObj.isCompatible(stoObj)) {
  41. if(oldObj.isRef) {
  42. oldObj.updateRef(stoObj);
  43. return this;
  44. }
  45. stoObj.setID(id);
  46. this.store[id] = Object.freeze(stoObj);
  47. return this;
  48. } else {
  49. // TODO: better error message
  50. throw new Error(`${oldObj.type} is not compatible with the value given`);
  51. }
  52. }
  53. }
  54. insertStore (id, stoObj) {
  55. if (this.store[id]) {
  56. // TODO: better error message
  57. throw new Error(`${id} is already defined`);
  58. }
  59. stoObj.setID(id);
  60. this.store[id] = Object.freeze(stoObj);
  61. return this;
  62. }
  63. }