import { ClassProvider , FactoryProvider , Injectable , Injector , ValueProvider , } from "@angular/core" ; import { DemoDataGenerator } from "./demo-data-generator" ; import { EntityMapperService } from "../entity/entity-mapper.service" ; import { LoggingService } from "../logging/logging.service" ; import { User } from "../user/user" ; /**
 * General config object to pass all initially register DemoDataGenerators
 * with `DemoDataModule.forRoot()`.
 *
 * see docs at  DemoDataModule export class DemoDataServiceConfig { /**
     * Providers for DemoDataGenerator service implementations to be registered for data generation.
     *
     * This may also include providers for services a DemoDataGenerator depends on.
     */ dataGeneratorProviders : ( ValueProvider | ClassProvider | FactoryProvider ) [ ] = [ ] ; } /**
 * The DemoDataService is the manager for all provided DemoDataGenerator implementations.
 * It serves as the central service to trigger the demo data generation into the database.
 *
 * To add more demo data generators, refer the documentation
 * [How to Generate Demo Data] {@link /additional-documentation/how-to-guides/generate-demo-data.html} @ Injectable ( ) export class DemoDataService { /** All registered demo data generator services */ readonly dataGenerators : DemoDataGenerator < any > [ ] = [ ] ; constructor ( private entityMapper , private loggingService , private injector , private config ) { this . registerAllProvidedDemoDataGenerators ( ) ; } private registerAllProvidedDemoDataGenerators ( ) { for ( const provider of this . config . dataGeneratorProviders ) { const service = this . injector . get < any > ( provider . provide ) ; if ( service && service instanceof DemoDataGenerator ) { this . dataGenerators . push ( service ) ; } } } /**
     * Trigger all registered DemoDataGenerator implementations to generate demo entities
     * and add all the generated entities to the Database.
     */ async publishDemoData ( ) { if ( ! ( await this . hasEmptyDatabase ( ) ) ) { return ; } this . dataGenerators . forEach ( ( generator ) => generator . entities ) ; for ( const generator of this . dataGenerators ) { for ( const entity of generator . entities ) { try { await this . entityMapper . save ( entity ) ; } catch ( e ) { this . loggingService . warn ( e ) ; } } } } async hasEmptyDatabase ( ) { const existingUsers = await this . entityMapper . loadType ( User ) ; return existingUsers . length === 0 ; } }