redoc/src/services/AppStore.ts

67 lines
1.5 KiB
TypeScript
Raw Normal View History

import { OpenAPISpec } from '../types';
2017-10-12 00:01:37 +03:00
import { SpecStore } from './models';
import { MenuStore } from './MenuStore';
import { ScrollService } from './ScrollService';
import { loadAndBundleSpec } from '../utils/loadAndBundleSpec';
2017-10-12 00:01:37 +03:00
type StoreData = {
menu: {
activeItemIdx: number;
};
spec: {
url: string;
data: any;
};
};
export async function createStore(spec: object, specUrl: string) {
const resolvedSpec = await loadAndBundleSpec(spec || specUrl);
return new AppStore(resolvedSpec, specUrl);
}
2017-10-12 00:01:37 +03:00
export class AppStore {
menu: MenuStore;
spec: SpecStore;
private scroll: ScrollService;
2017-10-12 00:01:37 +03:00
constructor(spec: OpenAPISpec, specUrl?: string) {
2017-10-12 00:01:37 +03:00
this.scroll = new ScrollService();
this.spec = new SpecStore(spec, specUrl);
2017-10-12 00:01:37 +03:00
this.menu = new MenuStore(this.spec, this.scroll);
}
dispose() {
this.scroll.dispose();
this.menu.dispose();
}
/**
* serializes store
* **SUPER HACKY AND NOT OPTIMAL IMPLEMENTATION**
*/
// TODO:
toJS(): StoreData {
2017-10-12 00:01:37 +03:00
return {
menu: {
activeItemIdx: this.menu.activeItemIdx,
2017-10-12 00:01:37 +03:00
},
spec: {
url: this.spec.parser.specUrl,
data: this.spec.parser.spec,
2017-10-12 00:01:37 +03:00
},
};
}
/**
* deserialize store
* **SUPER HACKY AND NOT OPTIMAL IMPLEMENTATION**
*/
// TODO:
static fromJS(state: StoreData): AppStore {
const inst = new AppStore(state.spec.data, state.spec.url);
2017-10-12 00:01:37 +03:00
inst.menu.activeItemIdx = state.menu.activeItemIdx || 0;
inst.menu.activate(inst.menu.flatItems[inst.menu.activeItemIdx]);
return inst;
}
}