All files / services/bootstrap bootstrap.service.ts

30.91% Statements 34/110
52.27% Branches 46/88
1.79% Functions 1/56
35.16% Lines 32/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212  1x 1x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x 1x 1x 1x 1x     1x     1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                                                                                                                                                                                                                                                                                                                                  
 
import { of, combineLatest, from, Observable, forkJoin } from 'rxjs';
import { Container, Service, PluginInterface } from '../../container';
import { BootstrapLogger } from '../bootstrap-logger/bootstrap-logger';
import { CacheService } from '../cache/cache-layer.service';
import { InternalLayers, InternalEvents } from '../../helpers/events';
import { LazyFactory } from '../lazy-factory/lazy-factory.service';
import { ConfigService } from '../config/config.service';
import { PluginService } from '../plugin/plugin.service';
import { ConfigModel } from '../config/config.model';
import { take, map, switchMap } from 'rxjs/operators';
import { CacheLayer, CacheLayerItem } from '../cache';
import { EffectsService } from '../effect/effect.service';
import { ControllersService } from '../controllers/controllers.service';
import { ComponentsService } from '../components/components.service';
import { BootstrapsServices } from '../bootstraps/bootstraps.service';
import { ServicesService } from '../services/services.service';
import { PluginManager } from '../plugin-manager/plugin-manager';
import { AfterStarterService } from '../after-starter/after-starter.service';
 
@Service()
export class BootstrapService {
 
    globalConfig: CacheLayer<CacheLayerItem<ConfigModel>>;
    chainableObservable = of(true);
    asyncChainables: Observable<any>[] = [this.chainableObservable];
    config: ConfigModel;
 
    constructor(
        private logger: BootstrapLogger,
        private cacheService: CacheService,
        private lazyFactoriesService: LazyFactory,
        public configService: ConfigService,
        private controllersService: ControllersService,
        private effectsService: EffectsService,
        private pluginService: PluginService,
        private componentsService: ComponentsService,
        private bootstrapsService: BootstrapsServices,
        private servicesService: ServicesService,
        private pluginManager: PluginManager,
        private afterStarterService: AfterStarterService
    ) {
        this.globalConfig = this.cacheService.createLayer<ConfigModel>({ name: InternalLayers.globalConfig });
    }
 
    public start(app, config?: ConfigModel): Observable<PluginManager> {
        this.configService.setConfig(config);
        this.globalConfig.putItem({ key: InternalEvents.init, data: config });
        Container.get(app);
        return of<string[]>(Array.from(this.lazyFactoriesService.lazyFactories.keys()))
            .pipe(
                map((i) => i.map(injectable => this.prepareAsyncChainables(injectable))),
                switchMap((res: Observable<Object>) => combineLatest(this.asyncChainables)
                    .pipe(
                        take(1),
                        map((c) => this.attachLazyLoadedChainables(res, c)),
                        map(() => this.validateSystem()),
                        switchMap(() => combineLatest(this.asyncChainableControllers())),
                        switchMap(() => combineLatest(this.asyncChainablePluginsBeforeRegister())),
                        switchMap(() => combineLatest(this.asyncChainablePluginsRegister())),
                        switchMap(() => combineLatest(this.asyncChainablePluginsAfterRegister())),
                        switchMap(() => combineLatest(this.asyncChainableServices())),
                        switchMap(() => combineLatest(this.asyncChainableEffects())),
                        switchMap(() => combineLatest(this.asyncChainableComponents())),
                        map(() => this.loadApplication()),
                        switchMap(() => combineLatest(this.asyncChainableBootstraps())),
                        map(() => this.final())
                    ))
            );
    }
 
    private final(): PluginManager {
        // opn('https://theft.youvolio.com');
        // const globalConfig = cache.createLayer<{ init: boolean }>({ name: InternalLayers.globalConfig });
        // cache.getLayer('AppModule').putItem({key:InternalEvents.load, data: true});
        // cache.getLayer('UserModule').putItem({ key: InternalEvents.load, data: true });
        // console.log('bla bla', plugins);!
        // Bootstrapping finished!
        this.afterStarterService.appStarted.next(true);
        return this.pluginManager;
    }
 
    private asyncChainablePluginsRegister() {
        const filter = (c) => this.configService.config.initOptions.plugins
            || c['metadata']['options'] && c['metadata']['options']['init']
            || this.configService.config.init;
        return [
            this.chainableObservable,
            ...this.pluginService.getPlugins()
                .filter(filter)
                .map(async c => this.registerPlugin(c))
        ];
    }
 
    private asyncChainableComponents() {
        const filter = (c) => this.configService.config.initOptions.components
            || c['metadata']['options'] && c['metadata']['options']['init']
            || this.configService.config.init;
        return [
            this.chainableObservable,
            ...this.componentsService.getComponents()
                .filter(filter)
                .map(async c => await Container.get(c))
        ];
    }
 
    private asyncChainableBootstraps() {
        return [
            this.chainableObservable,
            ...this.bootstrapsService.getBootstraps()
                .map(async c => await Container.get(c))
        ];
    }
 
    private asyncChainableEffects() {
        const filter = (c) => this.configService.config.initOptions.effects
            || c['metadata']['options'] && c['metadata']['options']['init']
            || this.configService.config.init;
        return [
            this.chainableObservable,
            ...this.effectsService.getEffects()
                .filter(filter)
                .map(async c => await Container.get(c))
        ];
    }
 
    private asyncChainableServices() {
        const filter = (c) => this.configService.config.initOptions.services
            || c['metadata']['options'] && c['metadata']['options']['init']
            || this.configService.config.init;
        return [
            this.chainableObservable,
            ...this.servicesService.getServices()
                .filter(filter)
                .map(async c => await Container.get(c))
        ];
    }
 
    private asyncChainableControllers() {
        const filter = (c) => this.configService.config.initOptions.controllers
            || c['metadata']['options'] && c['metadata']['options']['init']
            || this.configService.config.init;
        return [
            this.chainableObservable,
            ...this.controllersService.getControllers()
                .filter(filter)
                .map(async c => await Container.get(c))
        ];
    }
 
    private asyncChainablePluginsAfterRegister() {
        const filter = (c) => this.configService.config.initOptions.pluginsAfter
            || c['metadata']['options'] && c['metadata']['options']['init']
            || this.configService.config.init;
        return [
            this.chainableObservable,
            ...this.pluginService.getAfterPlugins()
                .filter(filter)
                .map(async c => await this.registerPlugin(c))
        ];
    }
 
    private asyncChainablePluginsBeforeRegister() {
        const filter = (c) => this.configService.config.initOptions.pluginsBefore
            || c['metadata']['options'] && c['metadata']['options']['init']
            || this.configService.config.init;
        return [
            this.chainableObservable,
            ...this.pluginService.getBeforePlugins()
                .filter(filter)
                .map(async c => this.registerPlugin(c))
        ];
    }
 
    private async registerPlugin(pluggable: Function | PluginInterface) {
        const plugin = Container.get<PluginInterface>(pluggable);
        await plugin.register();
        return plugin;
    }
 
    private prepareAsyncChainables(injectable: any) {
        this.logger.log(`Bootstrap -> @Service('${injectable.name || injectable}'): loading...`);
        const somethingAsync = from(<Promise<any> | Observable<any>>this.lazyFactoriesService.getLazyFactory(injectable));
        this.asyncChainables.push(somethingAsync);
        // somethingAsync
        //     .subscribe(
        //         () => this.logger.log(`Bootstrap -> @Service('${injectable.name || injectable}'): loading finished! ${new Date().toLocaleTimeString()}`)
        //     );
        return injectable;
    }
 
    private validateSystem() {
        this.cacheService.searchForDuplicateDependenciesInsideApp();
    }
 
    private attachLazyLoadedChainables(res, chainables) {
        // Remove first chainable unused observable
        chainables.splice(0, 1);
        let count = 0;
        res.map(name => Container.set(name, chainables[count++]));
        return true;
    }
 
    loadApplication() {
        this.logger.log('Bootstrap -> press start!');
        Array.from(this.cacheService.getLayer<Function>(InternalLayers.modules).map.keys())
            .forEach(m => this.cacheService.getLayer(m)
                .putItem({ key: InternalEvents.load, data: this.configService.config.init }));
        return true;
    }
 
}