2021-02-04 19:15:23 +01:00
|
|
|
import { ObservableStore } from '@metamask/obs-store';
|
2018-04-13 05:26:50 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* An ObservableStore that can composes a flat
|
|
|
|
* structure of child stores based on configuration
|
|
|
|
*/
|
2020-05-06 00:19:38 +02:00
|
|
|
export default class ComposableObservableStore extends ObservableStore {
|
2018-04-13 05:26:50 +02:00
|
|
|
/**
|
|
|
|
* Create a new store
|
|
|
|
*
|
|
|
|
* @param {Object} [initState] - The initial store state
|
|
|
|
* @param {Object} [config] - Map of internal state keys to child stores
|
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
constructor(initState, config) {
|
2021-02-04 19:15:23 +01:00
|
|
|
super(initState);
|
|
|
|
this.updateStructure(config);
|
2018-04-13 19:13:36 +02:00
|
|
|
}
|
2018-04-13 05:26:50 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Composes a new internal store subscription structure
|
|
|
|
*
|
|
|
|
* @param {Object} [config] - Map of internal state keys to child stores
|
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
updateStructure(config) {
|
2021-02-04 19:15:23 +01:00
|
|
|
this.config = config;
|
|
|
|
this.removeAllListeners();
|
2018-04-13 19:13:36 +02:00
|
|
|
for (const key in config) {
|
2020-08-13 22:34:51 +02:00
|
|
|
if (Object.prototype.hasOwnProperty.call(config, key)) {
|
2020-07-21 23:10:45 +02:00
|
|
|
config[key].subscribe((state) => {
|
2021-02-04 19:15:23 +01:00
|
|
|
this.updateState({ [key]: state });
|
|
|
|
});
|
2020-07-21 23:10:45 +02:00
|
|
|
}
|
2018-04-13 19:13:36 +02:00
|
|
|
}
|
2018-04-13 05:26:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Merges all child store state into a single object rather than
|
|
|
|
* returning an object keyed by child store class name
|
|
|
|
*
|
2020-11-10 18:30:41 +01:00
|
|
|
* @returns {Object} Object containing merged child store state
|
2018-04-13 05:26:50 +02:00
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
getFlatState() {
|
2021-02-04 19:15:23 +01:00
|
|
|
let flatState = {};
|
2018-04-13 05:26:50 +02:00
|
|
|
for (const key in this.config) {
|
2020-08-13 22:34:51 +02:00
|
|
|
if (Object.prototype.hasOwnProperty.call(this.config, key)) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const controller = this.config[key];
|
2020-11-03 00:41:28 +01:00
|
|
|
const state = controller.getState
|
|
|
|
? controller.getState()
|
2021-02-04 19:15:23 +01:00
|
|
|
: controller.state;
|
|
|
|
flatState = { ...flatState, ...state };
|
2020-07-21 23:10:45 +02:00
|
|
|
}
|
2018-04-13 05:26:50 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return flatState;
|
2018-04-13 05:26:50 +02:00
|
|
|
}
|
|
|
|
}
|