export interface MagicController { [key: string]: any; get(key: string): Promise; set(key: string, val: any): Promise; } export interface MagicConfig { modules: { [key: string]: { data: { [key: string]: any }; controller: MagicController; }; }; spinnerTimeout?: number; } export interface MagicModule { [dataItemName: string]: { pending: boolean; spinning: boolean; timeout: number; val: any; error: null; startTask(): void; finishTask(): void; pull(): Promise; push(): Promise; } } export class Magic { [key: string]: MagicModule; constructor(config: MagicConfig) { let modulesConfig = config.modules || {}; for(let moduleName of Object.keys(modulesConfig)) { let module = modulesConfig[moduleName] if(!module.data) { throw new Error(`Module ${moduleName} has no configured data`) } if(!module.controller) { throw new Error(`Module ${moduleName} has no configurred controller`) } for (let key of Object.keys(module.data)) { this[moduleName][key] = { pending: false, spinning: false, timeout: null, error: null, val: module.data[key], startTask() { this.pending = true; this.timeout = setTimeout( () => (this.spinning = true), config.spinnerTimeout || 2000 ); }, finishTask() { if (this.timeout) clearTimeout(this.timeout); this.pending = false; this.spinning = false; }, pull() { this.startTask(); return module.controller .get(key) .then(fetchedVal => { this.val = fetchedVal; this.finishTask(); return fetchedVal; }) .catch(err => { console.error(err); this.error = err; this.finishTask; }); }, push() { this.startTask(); return module.controller .set(key, this.val) .then(() => this.finishTask()) .catch(err => { console.error(err); this.error = err; this.finishTask; }); } }; this[moduleName][key].pull(); } } }