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);
|
2021-05-11 18:39:17 +02:00
|
|
|
if (config) {
|
|
|
|
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();
|
2021-05-11 18:39:17 +02:00
|
|
|
for (const key of Object.keys(this.config)) {
|
|
|
|
config[key].subscribe((state) => {
|
|
|
|
this.updateState({ [key]: state });
|
|
|
|
});
|
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-05-11 18:39:17 +02:00
|
|
|
if (!this.config) {
|
|
|
|
return {};
|
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
let flatState = {};
|
2021-05-11 18:39:17 +02:00
|
|
|
for (const key of Object.keys(this.config)) {
|
|
|
|
const controller = this.config[key];
|
|
|
|
const state = controller.getState
|
|
|
|
? controller.getState()
|
|
|
|
: controller.state;
|
|
|
|
flatState = { ...flatState, ...state };
|
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
|
|
|
}
|
|
|
|
}
|