typeorm#EntityManager TypeScript Examples

The following examples show how to use typeorm#EntityManager. 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: coachees.ts    From backend with MIT License 7 votes vote down vote up
export function coacheesToMatchQuery(manager: EntityManager): SelectQueryBuilder<Pupil> {
    return manager.createQueryBuilder()
        .select("p")
        .from(Pupil, "p")
        .where("p.active IS TRUE \
                AND p.verification IS NULL \
                AND p.isProjectCoachee IS TRUE \
                AND p.openProjectMatchRequestCount > 0 \
                AND p.projectFields <> '{}' \
                AND split_part(p.email, '@', 2) NOT IN (:...emailDomainExclusions)", { emailDomainExclusions: InvalidEmailDomains});
}
Example #2
Source File: comments.module.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Module({
  imports: [TypeOrmModule.forFeature([CommentEntity])],
  controllers: [CommentsController],
  providers: [
    CommentsService,
    CommentEntity,
    CommentSubscriber,
    {
      useValue: EntityManager,
      useClass: EntityManager,
      provide: EntityManager,
    },
  ],
})
export class CommentsModule {}
Example #3
Source File: paginate-array-result.ts    From barista with Apache License 2.0 6 votes vote down vote up
export async function PaginateRawQuery<T>(
  manager: EntityManager,
  rawSql: string,
  queryParameters: any[] = [],
  page: number,
  pageSize: number,
  dataTransformer: any = entity => ({}),
): Promise<GetManyDefaultResponse<T>> {
  const totalResult = await manager.query(`SELECT COUNT(*) FROM (${rawSql}) as Count`, queryParameters);
  const total = !isEmpty(totalResult) ? +totalResult[0].count : undefined;
  page = Math.max(0, page - 1);
  const paramsLength = queryParameters.length;
  const data = await manager.query(`${rawSql} OFFSET $${paramsLength + 1} LIMIT $${paramsLength + 2}`, [
    ...queryParameters,
    page * pageSize,
    pageSize,
  ]);

  return {
    count: data.length,
    data: data.map(_ => dataTransformer(_)),
    page: page + 1,
    total,
    pageCount: pageSize && total ? Math.ceil(total / pageSize) : undefined,
  };
}
Example #4
Source File: CashAccountService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async delete(id: string) {
        const dependentObjectList = await this.countDependentObject(id);
        if (dependentObjectList.some((item) => item.numberOfDep > 0)) {
            throw new Error("Can't delete this CashAccount because other objects depend on it.");
        }

        const account = await this.get(id);
        const splitSumList = await account?.cashSplitSumList;
        return await getManager().transaction(async (transactionalEntityManager: EntityManager) => {
            await transactionalEntityManager.remove(splitSumList);
            await transactionalEntityManager.remove(account);
        });
    }
Example #5
Source File: with-transaction.ts    From nest_transact with MIT License 6 votes vote down vote up
private findArgumentsForProvider(constructor: ClassType, manager: EntityManager, excluded: ClassType[]) {
    const args: any[] = [];
    const keys = Reflect.getMetadataKeys(constructor);
    keys.forEach((key) => {
      if (key === PARAMTYPES_METADATA) {
        const paramTypes: Array<string | ClassType> = Reflect.getMetadata(key, constructor);
        for (const param of paramTypes) {
          const argument = this.getArgument(param, manager, excluded);
          args.push(argument);
        }
      }
    });
    return new constructor(...args);
  }
Example #6
Source File: transactional.ts    From malagu with MIT License 6 votes vote down vote up
Transactional = <TransactionalDecorator>function (nameOrTransactionalOption?: string | TransactionalOption): MethodDecorator {
    const { name, isolation, propagation, readOnly } = getTransactionalOption(nameOrTransactionalOption);
    return (target: Object, methodName: string, descriptor: PropertyDescriptor) => {
        const originalMethod = descriptor.value;
        descriptor.value = async function (...args: any[]) {
            if (propagation === Propagation.Required) {
                const em = OrmContext.getEntityManager(name);
                if (em && em.queryRunner && (em.queryRunner.isTransactionActive || readOnly)) {
                    return originalMethod.apply(this, args);
                }
            }
            const callback = async (entityManager: EntityManager) => {

                OrmContext.pushEntityManager(name!, entityManager);
                try {
                    return await originalMethod.apply(this, args);
                } finally {
                    OrmContext.popEntityManager(name!);
                }
            };
            const conn = await getConnection(name);
            const manager = conn.manager;
            if (readOnly) {
                return callback(manager);
            } else if (isolation) {
                return manager.transaction(isolation, callback);
            } else {
                return manager.transaction(callback);
            }
        };

    };
}
Example #7
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
export async function matchMakingOfAllPossibleMatches(manager: EntityManager) {
    // get data for matching
    const coaches = await coachesToMatch(manager);
    const coachees = await coacheesToMatch(manager);

    //create matching
    const { matching, stats } = await createMatching(coaches, coachees, manager);

    //validate matching (including the current database state)
    const validationResult = await validateMatching(matching, manager);

    if (validationResult !== true) {
        // a problem occurred, validation failed
        const coachUUID = validationResult.match.helper.uuid;
        const coacheeUUID = validationResult.match.helpee.uuid;
        logger.warn(`Matching failed, because of ${validationResult.problem} for match between coach ${coachUUID} and coachee ${coacheeUUID}`);
        throw new Error(`Matching failed for match (coach: ${coachUUID}, coachee: ${coacheeUUID})!`);
    }

    //save matching in database (such that the database is in the state as the matching was performed)
    const databaseProjectMatches = await saveMatchingToDB(matching, manager);

    //notify all matches
    await notifyMatches(databaseProjectMatches, manager);

    logger.info(`Successfully created ${databaseProjectMatches.length} new project matches and notified the corresponding people`);
    logger.info(`Matches made: ${JSON.stringify(matching)}`);
    logger.info(`Matching stats: ${JSON.stringify(stats)}`);
}
Example #8
Source File: loadFakeData.script.ts    From rest-api.ts with MIT License 6 votes vote down vote up
async function createOrder(manager: EntityManager) {
  const user = await manager.save(User, generateUser());
  const owner = await manager.save(User, generateUser());
  const order = await manager.save(Order, generateOrder({user}));

  for (let j = 0; j < 5; j++) {
    const product = await manager.save(Product, generateProduct({user: owner}));
    await manager.save(Placement, {order, product, quantity: 2});
  }
}
Example #9
Source File: db.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
private async tx(cb: (em: EntityManager) => Promise<void>, attempt: number = 1): Promise<number> {
        try {
            await this.con.transaction(this.isolationLevel, cb)
            return attempt
        } catch(e: any) {
            if (e.code == '40001' && attempt < this.maxTxAttempts) {
                return this.tx(cb, attempt + 1)
            } else {
                throw e
            }
        }
    }
Example #10
Source File: app.service.ts    From NestJs-youtube with MIT License 5 votes vote down vote up
constructor(entityManager: EntityManager) {
    super(entityManager);
    this.fakeData();
  }
Example #11
Source File: CashSplitSumService.ts    From cashcash-desktop with MIT License 5 votes vote down vote up
async computeSplitSumList(
        toAddCashTransactionList: CashTransaction[],
        toRemoveCashTransactionList: CashTransaction[],
        transactionalEntityManager: EntityManager,
        toRemoveParameter?: TransactionParameters,
    ): Promise<CashSplitSum[]> {
        const cashAccountService = Container.get(CashAccountService);
        const internalLeafAccountIdList = (await cashAccountService.getInternalLeafList()).map(
            (item) => item.id,
        );

        // Get existing cashSplitSum
        const splitSumList = await this.getList(transactionalEntityManager);
        const sumByAccountIdCurrencyId: Map<string, CashSplitSum> = this.createMap(splitSumList);

        // Compute the substracted part
        const cashSplitRepository: CashSplitRepository = transactionalEntityManager.getCustomRepository(
            CashSplitRepository,
        );
        let oldCashSplitList: CashSplit[];
        if (toRemoveParameter) {
            oldCashSplitList = await cashSplitRepository.findCustom(toRemoveParameter);
        } else {
            const transactionIdList: number[] = toRemoveCashTransactionList
                .filter((transaction) => transaction.id != null)
                .map((transaction) => transaction.id);
            oldCashSplitList = await cashSplitRepository.findByTransactionId(transactionIdList);
        }

        oldCashSplitList = oldCashSplitList.filter((item) =>
            internalLeafAccountIdList.includes(item.accountId),
        );
        this.minus(sumByAccountIdCurrencyId, oldCashSplitList);

        // Compute the added part
        const newCashSplitList: CashSplit[] = _.flatMap(
            toAddCashTransactionList,
            (item: CashTransaction) => item.cashSplitList,
        ).filter((item) => internalLeafAccountIdList.includes(item.accountId));
        this.add(sumByAccountIdCurrencyId, newCashSplitList);

        return Array.from(sumByAccountIdCurrencyId.values());
    }
Example #12
Source File: with-transaction.d.ts    From nest_transact with MIT License 5 votes vote down vote up
withTransaction(manager: EntityManager, transactionOptions?: WithTransactionOptions): this;