typeorm#Connection TypeScript Examples

The following examples show how to use typeorm#Connection. 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: test-db-util.ts    From barista with Apache License 2.0 7 votes vote down vote up
static async resetEntities(seedData: boolean = false) {

    return new Promise(async (resolve) => {
      const connection: Connection = await this.seedConnection();

      await connection.synchronize(true).then(async () => {

        return connection.close().then(async () => {

          if (seedData) {
            await this.seedDb();
            resolve(true);
          } else {
            resolve(true);
          }
        });

      });

    });
  }
Example #2
Source File: index.ts    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
async initialize(): Promise<Connection> {
        const isDev = process.env.NODE_ENV !== "production";

        // If the DB is set, but not connected, try to connect
        if (this.db) {
            if (!this.db.isConnected) await this.db.connect();
            return this.db;
        }

        let dbPath = `${app.getPath("userData")}/config.db`;
        if (isDev) {
            dbPath = `${app.getPath("userData")}/bluebubbles-server/config.db`;
        }

        this.db = await createConnection({
            name: "config",
            type: "better-sqlite3",
            database: dbPath,
            entities: [Config, Alert, Device, Queue, Webhook, Contact, ContactAddress],
            // We should really use migrations for this.
            // This is me being lazy. Maybe someday...
            synchronize: true
        });

        // Load default config items
        await this.loadConfig();
        await this.setupDefaults();
        return this.db;
    }
Example #3
Source File: JtiLog.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
/**
     * Checks that the the given jti is unique by logging in the database, and checking for earlier entries in the log. Could be improved for more demanding performance needs by adding indexes for further claims.
     * @param jti 
     * @param iss 
     * @param sub 
     */
    constructor(@inject("Promise<Connection>") private connection:Promise<Connection>) {

    }
Example #4
Source File: app.controller.ts    From nest_transact with MIT License 6 votes vote down vote up
constructor(
    private readonly appService: AppService,
    private readonly appServiceV2: PurseSavingService,
    /**
     * This is deprecated in typeorm for now,
     * but the DataSource object still not injectable in Nest.js,
     * because of that we should use deprecated [Connection] until [DataSource]
     * will be injectable
     */
    private readonly connection: Connection,
  ) {
  }
Example #5
Source File: setup-data.seed.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
public async run(factory: Factory, connection: Connection): Promise<void> {
    console.log('quizSampleData', quizSampleData);
    await getManager().query('SET foreign_key_checks = 0');
    await getManager().query('TRUNCATE quizes');
    await getManager().query('TRUNCATE questions');
    await getManager().query('TRUNCATE options');
    await getManager().query('SET foreign_key_checks = 1');

    for (let i = 0; i < quizSampleData.length; i++) {
      const { quizTitle, quizDescription, questions } = quizSampleData[i];

      const quiz = new Quiz();
      quiz.title = quizTitle;
      quiz.description = quizDescription;
      await quiz.save();

      for (let j = 0; j < questions.length; j++) {
        const { question, options } = questions[j];

        const que = new Question();
        que.question = question;
        que.quiz = quiz;
        await que.save();

        for (let k = 0; k < options.length; k++) {
          const { isCorrect, text } = options[k];
          const opt = new Option();
          opt.isCorrect = isCorrect;
          opt.text = text;
          opt.question = que;
          await opt.save();
        }
      }
    }
  }
Example #6
Source File: db.ts    From prox2 with GNU Affero General Public License v3.0 6 votes vote down vote up
async function getConnection(): Promise<Connection> {
  const connManager = getConnectionManager();
  if (connManager.has("default")) {
    await connManager.get().close();
  }

  return await createConnection({
    type: "postgres",
    url: postgres_url,
    entities: [Confession],
    synchronize: true,
    logging: false,
  });
}
Example #7
Source File: dailyData.ts    From aqualink-app with MIT License 6 votes vote down vote up
export async function runDailyUpdate(conn: Connection) {
  const today = moment()
    .utc()
    .hours(23)
    .minutes(59)
    .seconds(59)
    .milliseconds(999);

  const yesterday = moment(today);
  yesterday.day(today.day() - 1);
  console.log(`Daily Update for data ending on ${yesterday.date()}`);
  try {
    await getSitesDailyData(conn, yesterday.toDate());
    console.log('Completed daily update.');
  } catch (error) {
    console.error(error);
  }
}
Example #8
Source File: CreateAdmin.seed.ts    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
public async run(factory: Factory, connection: Connection): Promise<any> {
    const admin = await UserEntity.createQueryBuilder('user')
      .where('user.email = :email', {email: EMAIL})
      .getOne();

    if (!admin) {
      await UserEntity.create({
        email: EMAIL,
        password: PASSWORD,
        isAdmin: true,
      }).save();
    }
  }
Example #9
Source File: scheduler.ts    From backend with MIT License 6 votes vote down vote up
function executeJob(job: (manager: EntityManager) => Promise<void>, jobConnectionGetter: () => Promise<Connection>): () => Promise<void> {
    return async function() { //return a real function, not an arrow-function here, because we need this to be set according to the context defined as part of the CronJob creation
        //"this" is the context of the cron-job -> see definition of node cron package
        this.stop(); //start stop, so that the same job is never executed in parallel

        try {
            //Get the connection that should be used to execute the job in
            //we assume that the returned connection is always active
            const connection = await jobConnectionGetter();

            //The entity manager that should be used to manage the entities
            const manager = connection.manager;

            //execute the job with the manager
            await job(manager);
        } catch (e) {
            logger.error(`Can't execute job: ${job.name} due to error with message: ${e.message}`);
            logger.debug(e);
        }

        this.start();
    };
}
Example #10
Source File: ModelStore.ts    From confidential-storage with Apache License 2.0 6 votes vote down vote up
constructor(connection: Connection, allowDataBaseDestruction: boolean) {
    this.connection = connection;
    this.allowDataBaseDestruction = allowDataBaseDestruction;
    this.vaults = connection.getMongoRepository(Vault);
    this.vaultIndexes = connection.getMongoRepository(VaultIndex);
    this.documents = connection.getMongoRepository(Document);
    this.capabilities = connection.getMongoRepository(Capability);
    this.revocations = connection.getMongoRepository(Revocation);
    this.chunks = connection.getMongoRepository(Chunk);
  }
Example #11
Source File: typeorm-uml.class.ts    From typeorm-uml with MIT License 6 votes vote down vote up
/**
	 * Creates and returns Typeorm connection based on selected configuration file.
	 *
	 * @async
	 * @private
	 * @param {string} configPath A path to Typeorm config file.
	 * @param {Flags} flags An object with command flags.
	 * @returns {Connection} A connection instance.
	 */
	private async getConnection( configPath: string, flags: Flags ): Promise<Connection> {
		let root = process.cwd();
		let configName = configPath;

		if ( isAbsolute( configName ) ) {
			root = dirname( configName );
			configName = basename( configName );
		}

		const cwd = dirname( resolve( root, configName ) );
		process.chdir( cwd );

		const connectionOptionsReader = new ConnectionOptionsReader( { root, configName } );
		const connectionOptions = await connectionOptionsReader.get( flags.connection || 'default' );
		return getConnectionManager().create( connectionOptions );
	}
Example #12
Source File: index.ts    From backend-postgres-typescript-node-express with MIT License 6 votes vote down vote up
export async function getConnection(): Promise<Connection> {
  if (connection) {
    return connection
  }

  connection = await createConnection()

  return connection
}
Example #13
Source File: database.service.ts    From rest-api.ts with MIT License 6 votes vote down vote up
public async getConnection(): Promise<Connection> {
    if (DatabaseService.connection instanceof Connection) {
      return DatabaseService.connection;
    }
    // const options = await getConnectionOptions(`orm_${new Date().getTime()}`);

    try {
      DatabaseService.connection = await createConnection();
      this.logger.log('INFO', `Connection established`);
    } catch (e) {
      this.logger.log('ERROR', 'Cannot establish database connection');
      process.exit(1);
    }

    return DatabaseService.connection;
  }
Example #14
Source File: bill.subscriber.ts    From bank-server with MIT License 6 votes vote down vote up
/*
    NOTE: It need to use different services,
    that's why this subscriber is connected by the constructor.
   */
  constructor(
    @InjectConnection() readonly connection: Connection,
    private readonly _messageService: MessageService,
    private readonly _messageKeyService: MessageKeyService,
    private readonly _userService: UserService,
    private readonly _userAuthService: UserAuthService,
    private readonly _languageService: LanguageService,
    private readonly _transactionService: TransactionService,
    private readonly _billService: BillService,
  ) {
    connection.subscribers.push(this);
  }
Example #15
Source File: MediaModule.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
persistenceProviders: Provider[] = [
  {
    provide : MediaDITokens.MediaFileStorage,
    useClass: MinioMediaFileStorageAdapter,
  },
  {
    provide   : MediaDITokens.MediaRepository,
    useFactory: connection => connection.getCustomRepository(TypeOrmMediaRepositoryAdapter),
    inject    : [Connection]
  }
]
Example #16
Source File: DatabaseContainer.ts    From ZenTS with MIT License 6 votes vote down vote up
constructor(dbConnection: Connection | null, redisClient: Redis | null) {
    if (dbConnection) {
      this.container.set(DB_TYPE.ORM, dbConnection)
    }

    if (redisClient) {
      this.container.set(DB_TYPE.REDIS, redisClient)
    }
  }
Example #17
Source File: question.subscriber.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
constructor(
    connection: Connection,
    notifService: NotificationService,
    queueSSEService: QueueSSEService,
  ) {
    this.notifService = notifService;
    this.queueSSEService = queueSSEService;
    connection.subscribers.push(this);
  }
Example #18
Source File: ExplicitLoaderImpl.ts    From type-graphql-dataloader with MIT License 6 votes vote down vote up
constructor(relation: RelationMetadata, connection: Connection) {
    super(
      directLoader(
        relation,
        connection,
        relation.inverseEntityMetadata.primaryColumns[0].propertyName
      )
    );
  }
Example #19
Source File: CreateOrderStatus.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public async seed(factory: Factory, connection: Connection): Promise<OrderStatus> {
        const em = connection.createEntityManager();
        const statusData: any = [
            {
            orderStatusId: 1,
            name: 'In Progress',
            isActive: 1,
            },
            {
                orderStatusId: 2,
                name: 'Shipped',
                isActive: 1,
            },
            {
                orderStatusId: 3,
                name: 'Delivered',
                isActive: 1,
            },
            {
                orderStatusId: 4,
                name: 'completed',
                isActive: 1,
            },
        ];
        let i = 0;
            for ( i; i < statusData.length; i++ ) {
                const orderStatus = new OrderStatus();
                    orderStatus.orderStatusId = statusData[i].orderStatusId;
                    orderStatus.name = statusData[i].name;
                    orderStatus.isActive = statusData[i].isActive;
                    await em.save(orderStatus);
                }
        return statusData;
    }
Example #20
Source File: IndexerStarter.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Run migrations in the "migrations" folder;
   */
  static async migrate(): Promise<void> {
    let connection: Connection | undefined
    try {
      connection = await createDBConnection()
      if (connection) await connection.runMigrations()
    } finally {
      if (connection) await connection.close()
    }
  }
Example #21
Source File: db.ts    From node-typescript-starter-kit with MIT License 6 votes vote down vote up
DBConnect = async () => {
  let connection: Connection | undefined;
  try {
    connection = getConnection();
  } catch (e) {
  }

  try {
    if (connection) {
      if (!connection.isConnected) {
        await connection.connect();
      }
    } else {
      await createConnection(ORMConfig);
    }
    console.log("? Database connection was successful!");
  } catch (e) {
    console.error('ERROR: Database connection failed!!', e);
    throw e;
  }
}
Example #22
Source File: index.ts    From bluebubbles-server with Apache License 2.0 5 votes vote down vote up
db: Connection = null;
Example #23
Source File: Pagination.ts    From Designer-Server with GNU General Public License v3.0 5 votes vote down vote up
constructor(type: ObjectType<T>, connection: Connection) {
    this.type = type;
  }
Example #24
Source File: TypeORMCreateConnection.ts    From node-experience with MIT License 5 votes vote down vote up
private connection: Connection;
Example #25
Source File: Transaction.spec.ts    From rocketseat-gostack-11-desafios with MIT License 5 votes vote down vote up
connection: Connection
Example #26
Source File: App.ts    From context-mod with MIT License 5 votes vote down vote up
database: Connection
Example #27
Source File: auth.test.ts    From jaebook-server with MIT License 5 votes vote down vote up
db: Connection
Example #28
Source File: Dependencies.ts    From ADR-Gateway with MIT License 5 votes vote down vote up
async function RegisterDependencies(configFn:() => Promise<AdrConnectivityConfig>, db?: Promise<Connection>): Promise<void> {
    let config = await configFn();

    const level = process.env.LOG_LEVEL || "warn";

    const transports:Transport[] = [
        new winston.transports.Console({
            handleExceptions: true,
            level
        }),
    ];
    if (process.env.LOG_FILE) {
        transports.push(new winston.transports.File({ filename: process.env.LOG_FILE, level }))
    }

    const logger = winston.createLogger({
        transports,
        exitOnError: false,
        format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.json({
                replacer: combineReplacers(errorReplacer,configReplacer,axiosReplacer)
            })
        )
    });


    let connection = db || (() => {
        let options = _.merge(EntityDefaults, config.Database);
        return createConnection(options)

    })()

    container.register<Promise<Connection>>(
        "Promise<Connection>",
        {
            useValue: connection
        });

    container.register("Logger", { useValue: logger })

    if (process.env.ADR_BACKEND_EXPOSE_ECOSYSTEM_ERRORS === "true") {
        container.register("EcosystemErrorFilter", { useValue: GenerousEcosystemErrorFilter })
    } else {
        container.register("EcosystemErrorFilter", { useValue: SecretiveEcosystemErrorFilter })
    }

    container.register("DataHolderMetadataProvider", { useClass: SelfHealingDataHolderMetadataProvider })

    // TODO replace the DevClientCertificate injector headers with actual certificate made with node-forge
    if (config.mtls?.ca) {
        container.register("ClientCertificateInjector", {
            useValue: new DefaultClientCertificateInjector(
                config.mtls
            )
        })
    } else {
        container.register("ClientCertificateInjector", { useClass: DevClientCertificateInjector })
    }

    container.register("AdrConnectivityConfig", { useValue: configFn })
    container.register("AdrGatewayConfig", { useValue: configFn }) // TODO cleanup so there is only one config
    container.register("Cache", { useValue: new DefaultCache() })

}
Example #29
Source File: augment-site-data.ts    From aqualink-app with MIT License 5 votes vote down vote up
async function augmentSites(connection: Connection) {
  const siteRepository = connection.getRepository(Site);
  const regionRepository = connection.getRepository(Region);
  const HistoricalMonthlyMeanRepository = connection.getRepository(
    HistoricalMonthlyMean,
  );
  const allSites = await siteRepository.find();

  const start = new Date();
  console.log(`Augmenting ${allSites.length} sites...`);
  await Bluebird.map(
    allSites,
    async (site) => {
      const augmentedData = await getAugmentedData(site, regionRepository);
      await siteRepository.update(site.id, augmentedData);
      // Add HistoricalMonthlyMeans
      const [longitude, latitude] = (site.polygon as Point).coordinates;
      const HistoricalMonthlyMeans = await getHistoricalMonthlyMeans(
        longitude,
        latitude,
      );
      await Promise.all(
        HistoricalMonthlyMeans.map(async ({ month, temperature }) => {
          try {
            await (temperature &&
              HistoricalMonthlyMeanRepository.insert({
                site,
                month,
                temperature,
              }));
          } catch {
            console.warn(
              `Monthly max values not imported for ${site.id} - the data was likely there already.`,
            );
          }
        }),
      );
    },
    { concurrency: 1 },
  );
  console.log(
    `Augmented ${allSites.length} sites in ${
      (new Date().valueOf() - start.valueOf()) / 1000
    } seconds`,
  );
}