@nestjs/common#OnApplicationBootstrap TypeScript Examples

The following examples show how to use @nestjs/common#OnApplicationBootstrap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: list.module.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
@Module({
    exports: [],
    imports: [SystemModule],
    providers: [],
})
export class ListModule implements OnApplicationBootstrap {
    constructor(
        @Inject('PARSED_PROVIDER') protected readonly parsed: ParsedInput<typeof InstallCommand>,
        @Inject('UTILS_PROVIDER') protected readonly utils: CommandUtils,
        @Inject(SystemProvider) protected readonly systemProvider: SystemProvider,
    ) {}

    async onApplicationBootstrap(): Promise<void> {
        const {flags} = this.parsed;
        const {environment: environmentId} = flags;

        const environment = await this.systemProvider.getEnvironment(environmentId);
        const installed = await environment.extensions.list();

        cli.table(
            installed.toArray(),
            {
                name: {},
                type: {},
                official: {},
                verification: {header: 'Verified'},
                version: {},
            },
            {
                printLine: this.utils.log,
                ...flags,
            },
        );
    }
}
Example #2
Source File: app.service.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Injectable()
export class AppService implements OnApplicationBootstrap {
  constructor(private licenseService: LicenseService) {}
  logger = new Logger('AppService');

  appStatus(): any {
    return {
      appName: 'barista-api',
      appEnvironment,
      appVersion,
      appCommitHash,
      nodeEnv: process.env.NODE_ENV,
      appMetaData: {
        authType: process.env.AUTH_TYPE,
      },
    };
  }

  async onApplicationBootstrap(): Promise<any> {
    this.logger.warn(this.prettyAppStatus());
    return this.licenseService.refreshLicenses();
  }

  prettyAppStatus(): string {
    const appInfo = this.appStatus();
    return JSON.stringify(appInfo, null, 4);
  }
}
Example #3
Source File: link.module.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
@Module({
    exports: [],
    imports: [SystemModule],
    providers: [],
})
export class LinkModule implements OnApplicationBootstrap {
    constructor(
        @Inject('PARSED_PROVIDER') protected readonly parsed: ParsedInput<typeof LinkCommand>,
        @Inject('UTILS_PROVIDER') protected readonly utils: CommandUtils,
        @Inject(SystemProvider) protected readonly systemProvider: SystemProvider,
    ) {}

    async onApplicationBootstrap(): Promise<void> {
        const {args, flags} = this.parsed;
        const {filePath} = args;
        const {projects} = await this.systemProvider.getEnvironment();

        const resolvedPath = path.resolve(filePath);
        const name = flags.name || (await inputPrompt('Enter the project name'));

        return projects.link(resolvedPath, name).then((res) => {
            this.utils.log(res.name);
        });
    }
}
Example #4
Source File: InfrastructureModule.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Global()
@Module({
  imports: [
    CqrsModule,
    TypeOrmModule.forRoot({
      name                     : 'default',
      type                     : 'postgres',
      host                     : DatabaseConfig.DB_HOST,
      port                     : DatabaseConfig.DB_PORT,
      username                 : DatabaseConfig.DB_USERNAME,
      password                 : DatabaseConfig.DB_PASSWORD,
      database                 : DatabaseConfig.DB_NAME,
      logging                  : DatabaseConfig.DB_LOG_ENABLE ? 'all' : false,
      logger                   : DatabaseConfig.DB_LOG_ENABLE ? TypeOrmLogger.new() : undefined,
      entities                 : [`${TypeOrmDirectory}/entity/**/*{.ts,.js}`],
      migrationsRun            : true,
      migrations               : [`${TypeOrmDirectory}/migration/**/*{.ts,.js}`],
      migrationsTransactionMode: 'all',
    })
  ],
  providers: providers,
  exports: [
    CoreDITokens.CommandBus,
    CoreDITokens.QueryBus,
    CoreDITokens.EventBus,
  ]
})
export class InfrastructureModule implements OnApplicationBootstrap {
  onApplicationBootstrap(): void {
    initializeTransactionalContext();
  }
}
Example #5
Source File: create.module.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
@Module({
    exports: [],
    imports: [SystemModule],
    providers: [],
})
export class CreateModule implements OnApplicationBootstrap {
    constructor(
        @Inject('PARSED_PROVIDER')
        protected readonly parsed: ParsedInput<typeof CreateCommand>,
        @Inject('UTILS_PROVIDER') protected readonly utils: CommandUtils,
        @Inject(SystemProvider) protected readonly systemProvider: SystemProvider,
    ) {}

    async onApplicationBootstrap(): Promise<void> {
        const {args, flags} = this.parsed;
        const {environment: environmentId} = flags;
        const environment = await this.systemProvider.getEnvironment(environmentId);
        let {entityNameOrId} = args;
        const entityType = flags.type || (await selectPrompt('Select entity type to backup', VALID_BACKUP_TYPES));

        if (!entityNameOrId) {
            entityNameOrId = await selectEntityPrompt(`Select ${entityType} to backup`, environment, entityType);
        }

        const entity = await getSelectedEntity(environment, entityType, entityNameOrId);

        cli.action.start(`Creating backup for ${getEntityDisplayName(entity)}`);
        await environment.backups.create(entityType, entity.id);
        cli.action.stop();
    }
}
Example #6
Source File: boot.service.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
@Injectable()
export class BootService implements OnApplicationBootstrap {
  constructor(
    private readonly createService: UserCreateService,
    private readonly userService: UserService,
    private readonly configService: ConfigService,
    private readonly logger: PinoLogger,
  ) {
    logger.setContext(this.constructor.name)
  }

  async onApplicationBootstrap(): Promise<void> {
    const create = this.configService.get<string>('CREATE_ADMIN', 'false')

    if (!create || [
      'false', '0', 'no', '',
    ].includes(create.toLowerCase())) {
      return
    }

    this.logger.warn('admin user check is still enabled! once your use has been created this should be disabled')

    const username = this.configService.get<string>('ADMIN_USERNAME', 'root')
    const email = this.configService.get<string>('ADMIN_EMAIL', '[email protected]')
    const password = this.configService.get<string>('ADMIN_PASSWORD', 'root')

    if (await this.userService.usernameInUse(username)) {
      this.logger.info('username already exists, skip creating')
      return
    }

    if (await this.userService.emailInUse(email)) {
      this.logger.info('email already exists, skip creating')
      return
    }

    try {
      await this.createService.create({
        username,
        email,
        password,
      }, [
        'user', 'admin', 'superuser',
      ])
    } catch (e) {
      this.logger.error({
        error: serializeError(e),
      }, 'could not create admin user')
      return
    }

    this.logger.info('new root user created')
  }
}
Example #7
Source File: add-dbms.module.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
@Module({
    exports: [],
    imports: [SystemModule],
    providers: [],
})
export class AddDbmsModule implements OnApplicationBootstrap {
    constructor(
        @Inject('PARSED_PROVIDER') protected readonly parsed: ParsedInput<typeof AddDbmsCommand>,
        @Inject('UTILS_PROVIDER') protected readonly utils: CommandUtils,
        @Inject(SystemProvider) protected readonly systemProvider: SystemProvider,
    ) {}

    async onApplicationBootstrap(): Promise<void> {
        const {args, flags} = this.parsed;
        const environment = await this.systemProvider.getEnvironment(flags.environment);
        const projectName = flags.project || (await selectProjectPrompt('Select a Project', environment));
        const project = await environment.projects.get(projectName);

        const dbmsId =
            args.dbms || (await selectDbmsPrompt('Select a DBMS to create an access token for', environment));
        const dbmsName = flags.name || (await inputPrompt('Enter the DBMS project name'));
        const principal = flags.user || (await inputPrompt('Enter a Neo4j DBMS user'));
        const credentials = await passwordPrompt('Enter passphrase');

        const dbms = await environment.dbmss.get(dbmsId);
        const authToken = new AuthTokenModel({
            credentials,
            principal,
            scheme: 'basic',
        });

        cli.action.start('Creating access token');
        registerHookListener(HOOK_EVENTS.DBMS_TO_BE_ONLINE_ATTEMPTS, ({currentAttempt}) => {
            if (currentAttempt < 2) {
                return;
            }

            if (currentAttempt === 2) {
                this.utils.warn('DBMS connection not available, retrying...');
                return;
            }

            this.utils.warn('still retrying...');
        });
        cli.action.stop();

        return environment.dbmss
            .createAccessToken(project.name, dbms.id, authToken)
            .then((accessToken) =>
                environment.projects.addDbms(project.name, dbmsName, dbms.id, principal, accessToken),
            )
            .then(({name}) => this.utils.log(`Dbms ${name} added to project`));
    }
}