redoc/src/services/AppStore.ts

78 lines
2.0 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-11-21 14:00:33 +03:00
import { RedocNormalizedOptions, RedocRawOptions } from './RedocNormalizedOptions';
2017-10-12 00:01:37 +03:00
type StoreData = {
menu: {
activeItemIdx: number;
};
spec: {
url: string;
data: any;
};
2017-11-21 14:00:33 +03:00
options: RedocRawOptions;
};
2017-11-21 14:00:33 +03:00
export async function createStore(
spec: object,
specUrl: string | undefined,
options: RedocRawOptions = {},
) {
const resolvedSpec = await loadAndBundleSpec(spec || specUrl);
2017-11-21 14:00:33 +03:00
return new AppStore(resolvedSpec, specUrl, options);
}
2017-10-12 00:01:37 +03:00
export class AppStore {
menu: MenuStore;
spec: SpecStore;
2017-11-21 14:00:33 +03:00
rawOptions: RedocRawOptions;
options: RedocNormalizedOptions;
2017-10-12 00:01:37 +03:00
private scroll: ScrollService;
2017-10-12 00:01:37 +03:00
2017-11-21 14:00:33 +03:00
constructor(spec: OpenAPISpec, specUrl?: string, options: RedocRawOptions = {}) {
this.rawOptions = options;
this.options = new RedocNormalizedOptions(options);
this.scroll = new ScrollService(this.options);
2017-11-21 14:00:33 +03:00
this.spec = new SpecStore(spec, specUrl, this.options);
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
},
2017-11-21 14:00:33 +03:00
options: this.rawOptions,
2017-10-12 00:01:37 +03:00
};
}
/**
* deserialize store
* **SUPER HACKY AND NOT OPTIMAL IMPLEMENTATION**
*/
// TODO:
static fromJS(state: StoreData): AppStore {
2017-11-21 14:00:33 +03:00
const inst = new AppStore(state.spec.data, state.spec.url, state.options);
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;
}
}