typeorm#getManager TypeScript Examples

The following examples show how to use typeorm#getManager. 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: plugin-newsletter.controller.ts    From Cromwell with MIT License 7 votes vote down vote up
@Post('subscribe')
    /** Use ThrottlerGuard to limit number of requests from one IP address. Allow max 4 requests in 20 seconds: */
    @UseGuards(ThrottlerGuard)
    @Throttle(4, 20)
    @ApiOperation({ description: 'Post email to subscribe for newsletters' })
    @ApiResponse({
        status: 200,
        type: Boolean,
    })
    @ApiBody({ type: PluginNewsletterSubscription })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async placeSubscription(@Body() input: PluginNewsletterSubscription): Promise<boolean | undefined> {
        const email = input?.email;
        if (!email || !/\S+@\S+\.\S+/.test(email)) {
            throw new HttpException(`Invalid email`, HttpStatus.BAD_REQUEST);
        }

        const hasSubscribed = await getManager().findOne(PluginNewsletter, {
            where: {
                email
            }
        });
        if (hasSubscribed) return true;

        const newsletter = new PluginNewsletter();
        newsletter.email = email;
        await getManager().save(newsletter);
        return true;
    }
Example #2
Source File: team.utils.ts    From liferay-grow with MIT License 7 votes vote down vote up
getUserDetailsIdsByTeam = async (
  teamId: string,
): Promise<string[] | null> => {
  const manager = getManager();

  const userDetailsTeams = await manager
    .createQueryBuilder('user_details_teams', 'udt')
    .where('udt.teamId = :teamId', { teamId })
    .execute();

  if (!userDetailsTeams.length) {
    return null;
  }

  const userDetailsIds = userDetailsTeams.map(
    ({ udt_userDetailsId }: any) => udt_userDetailsId,
  );

  return userDetailsIds;
}
Example #3
Source File: CashCurrencyService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async find(isoCode1: string, manager?: EntityManager) {
        const criteria: FindOneOptions<CashCurrency> = {
            select: ['id', 'name', 'isoCode', 'symbol'],
            where: {
                isoCode: isoCode1,
            },
        };

        if (!manager) {
            manager = getManager();
        }
        const repository = manager.getCustomRepository(CashCurrencyRepository);
        return await repository.findOne(criteria);
    }
Example #4
Source File: bot-info-service.ts    From aiyou-wechaty-robot with Mozilla Public License 2.0 6 votes vote down vote up
static async selectCurrentInfo() {
    const botInfoRepository = getManager().getRepository(BotInfo);

    // const result = await botInfoRepository.find({
    //     order: {
    //         id: 'DESC'
    //   },
    //   skip: 0,
    //   take: 1
    // });
    const result = await botInfoRepository.findOne({
        order: {
            id: 'DESC'
      }
    });

    return result;
  }
Example #5
Source File: CashRateService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async removeRate(currencyId1: number, currencyId2: number) {
        const repository = getManager().getCustomRepository(CashRateRepository);
        const currencyIdList = [currencyId1, currencyId2];
        const rateList: CashRate[] = await repository.find({
            select: ['id'],
            where: {
                fromCurrencyId: In(currencyIdList),
                toCurrencyId: In(currencyIdList),
            },
        });
        this.cache.clear();
        await repository.remove(rateList);
    }
Example #6
Source File: group-record-service.ts    From aiyou-wechaty-robot with Mozilla Public License 2.0 6 votes vote down vote up
static async getTable() {
    const botMessageRepository = getManager().getRepository(BotMessage);
    const result = await botMessageRepository.find({
      skip: 0,
      take: 100,
    });

    return result;
  }
Example #7
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 #8
Source File: CashRateService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async save(cashRate: CashRate) {
        return await getManager().transaction(async (transactionalEntityManager) => {
            const repo = transactionalEntityManager.getCustomRepository(CashRateRepository);
            const oldCashRate = await this.getByCurrency(
                cashRate.fromCurrencyId,
                cashRate.toCurrencyId,
            );
            if (oldCashRate && oldCashRate.id !== cashRate.id) {
                await repo.delete(oldCashRate.id);
            }
            this.cache.clear();
            return await repo.save(cashRate);
        });
    }
Example #9
Source File: user-create.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> {
    await getManager().query('TRUNCATE users');
    await factory(User)().create({
      name: 'Amitav Roy',
      email: '[email protected]',
      password: 'Password@123',
      role: UserRoles.ADMIN,
    });
    // await factory(User)().createMany(20);
  }
Example #10
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
/* Pupils can retrieve certificates of their students, students can retrieve theirs */
export async function getCertificatesFor(user: Pupil | Student) {
    const entityManager = getManager();

    const certificatesData = await entityManager.find(ParticipationCertificate, {
        where: user instanceof Pupil ? { pupil: user.id } : { student: user.id },
        relations: ["student", "pupil"]
    });

    return certificatesData.map(cert => exposeCertificate(cert, /*to*/ user));
}
Example #11
Source File: CashRateService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async getByCurrency(
        fromCurrencyId: number,
        toCurrencyId: number,
    ): Promise<CashRate | undefined> {
        const key = this.createKey(fromCurrencyId, toCurrencyId);
        const cachedRate = this.cache.get(key);
        if (cachedRate) {
            return cachedRate;
        } else {
            const repo = getManager().getCustomRepository(CashRateRepository);
            const result = await repo.findOne({
                select: ['id', 'fromCurrencyId', 'toCurrencyId', 'rate', 'updatedDate'],
                where: {
                    fromCurrencyId,
                    toCurrencyId,
                },
                order: {
                    updatedDate: 'DESC',
                },
            });
            if (result) {
                this.cache.set(key, result);
            }
            return result;
        }
    }
Example #12
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
/* Students can download their certificates as PDF */
export async function getCertificatePDF(certificateId: string, _requestor: Student | PrismaStudent, lang: Language): Promise<Buffer> {
    const entityManager = getManager();

    const requestor = await entityManager.findOneOrFail(Student, { id: _requestor.id });

    /* Retrieve the certificate and also get the signature columns that are usually hidden for performance reasons */
    const certificate = await entityManager.findOne(ParticipationCertificate, { uuid: certificateId.toUpperCase(), student: requestor }, {
        relations: ["student", "pupil"],
        /* Unfortunately there is no "*" option which would also select the signatures. The query builder also does not cover this case */
        select: ["uuid", "categories", "certificateDate", "endDate", "hoursPerWeek", "hoursTotal", "id", "medium", "ongoingLessons", "signatureParent", "signaturePupil", "signatureDate", "signatureLocation", "startDate", "state", "subjects"]
    });

    if (!certificate) {
        throw new CertificateError("Certificate not found");
    }

    const pdf = await createPDFBinary(
        certificate,
        getCertificateLink(certificate, lang),
        lang as Language
    );

    return pdf;
}
Example #13
Source File: CashPreferenceService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async reset(): Promise<CashPreferences> {
        this.delete();
        const repo = getManager().getCustomRepository(CashPreferencesRepository);
        const cashPreferences = new CashPreferences();
        const cashCurrencyService = Container.get(CashCurrencyService);
        const currency = await cashCurrencyService.find('USD');
        if (currency) {
            cashPreferences.preferedCurrencyId = currency.id;
        }
        return await repo.save(cashPreferences);
    }
Example #14
Source File: Course.ts    From backend with MIT License 6 votes vote down vote up
async updateCourse(update: ApiCourseUpdate) {
        if (!update.isValid()) {
            throw new Error("Cannot use invalid ApiCourseUpdate to update course!");
        }

        if (update.instructors) {
            update.instructors = await Promise.all(update.instructors.map(it => getManager().findOneOrFail(Student, { where: { id: it.id, isInstructor: true }})));
        }

        for (const [key, value] of Object.entries(update)) {
            if (typeof value !== "undefined") {
                this[key] = value;
            }
        }
    }
Example #15
Source File: CashFilterService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async delete(id: string) {
        return await getManager().transaction(async (entityManager: EntityManager) => {
            const item: CashFilter | undefined = await this.get(id)!;
            if (item) {
                for (const rule of await item.cashRuleList) {
                    await entityManager.remove(rule);
                    await entityManager.remove(rule.action);
                }
                await entityManager.remove(item);
            }
        });
    }
Example #16
Source File: bbb.ts    From backend with MIT License 6 votes vote down vote up
export async function createBBBMeeting(name: string, id: string, user: Pupil | Student): Promise<BBBMeeting> {
    const entityManager = getManager();
    const transactionLog = getTransactionLog();
    const attendeePW = hashToken('' + Math.random(), "sha1");
    const moderatorPW = hashToken('' + Math.random(), "sha1");
    const bbbMeeting = new BBBMeeting();

    try {
        // Create new BBBMeeting
        bbbMeeting.meetingID = id;
        bbbMeeting.meetingName = name;
        bbbMeeting.moderatorPW = moderatorPW;
        bbbMeeting.attendeePW = attendeePW;
        await entityManager.save(BBBMeeting, bbbMeeting);
        await transactionLog.log(new CreateBBBMeetingEvent(user, bbbMeeting));
        logger.info("Successfully saved new bbb meeting with id ", bbbMeeting.meetingID);
        return bbbMeeting;
    } catch (e) {
        logger.error("Can't save new bbb meeting: " + e.message);
        logger.debug(bbbMeeting, e);
    }
}
Example #17
Source File: CashFilterService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async get(id: string): Promise<CashFilter | undefined> {
        const repo = getManager().getCustomRepository(CashFilterRepository);
        const item = await repo.findOne(id, {
            relations: ['cashAccountList', 'cashRuleList', 'cashRuleList.action'],
        });
        if (
            item &&
            item.jsonFilter.list.some((item) => item.fieldName === FieldNameDetectionType.TAG)
        ) {
            const tagRepo = getManager().getCustomRepository(CashTagRepository);
            const existingTagIdList = (await tagRepo.find()).map((item) => item.id);
            const cleanedUpList = item.jsonFilter.list.filter((item) => {
                if (item.fieldName !== FieldNameDetectionType.TAG) {
                    return true;
                }
                return existingTagIdList.includes(+item.parameter);
            });
            item.jsonFilter.list = cleanedUpList;
        }
        return item;
    }
Example #18
Source File: bbb.ts    From backend with MIT License 6 votes vote down vote up
export async function handleBBBMeetingInfos() {
    const entityManager = getManager();
    const meetings = await getRunningBBBMeetings();
    if (meetings != null) {
        for (const meeting of meetings) {
            const meetingAttendees = await getRunningBBBMeetingAttendees(meeting.meetingID);
            if (meetingAttendees != null) {
                const map = new Map();
                const filteredMeetingAttendees: Attendee[] = [];
                for (const attendee of meetingAttendees) {
                    if (!map.has(attendee.wix_id)) {
                        map.set(attendee.wix_id, true);
                        filteredMeetingAttendees.push(attendee);
                    }
                }
                for (const attendee of filteredMeetingAttendees) {
                    if (attendee.role && attendee.role === "VIEWER") {
                        const pupilFromDB = await entityManager.findOne(Pupil, {wix_id: attendee.wix_id});
                        if (pupilFromDB) {
                            await createOrUpdateCourseAttendanceLog(pupilFromDB, null, meeting.meetingID);
                        } else {
                            logger.error("Can't find attendee in db: " + attendee.fullName);
                        }
                    }
                }
            } else {
                logger.error("Can't get bbb meeting attendees.");
            }
        }
    } else {
        logger.error("Can't get bbb meetings.");
    }
}
Example #19
Source File: CashBudgetTransactionService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async deleteList(idList: string[]) {
        const cashTransactionList = await this.getList(idList);
        if (cashTransactionList.length === 0 || idList.length !== cashTransactionList.length) {
            // Not the same size or zero
            return;
        }
        const repo = getManager().getCustomRepository(CashBudgetTransactionRepository);
        return await repo.remove(cashTransactionList);
    }
Example #20
Source File: plugin-newsletter.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
/** 
     * The same method as pluginNewsletterStats in PluginNewsletterResolver. 
     * Added for documentation purposes of custom Controllers.
     * */
    @Get('stats')
    /** You can restrict route by assigning JwtAuthGuard and passing allowed roles as a decorator: */
    @UseGuards(JwtAuthGuard)
    @Roles('administrator', 'guest', 'author')
    @ApiOperation({ description: 'Get newsletters count' })
    @ApiResponse({
        status: 200,
        type: String,
    })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async getStats(@Request() request: TRequestWithUser): Promise<string> {

        // Or you can retrieve user info and validate permissions in the method:
        const allowedRoles: TUserRole[] = ['administrator', 'guest', 'author'];
        if (!allowedRoles.includes(request.user?.role))
            throw new ForbiddenException('Forbidden');

        return (await getManager().find(PluginNewsletter) ?? []).length + '';
    }
Example #21
Source File: queries.ts    From liferay-grow with MIT License 6 votes vote down vote up
getKnowledgeSummaryCount = (skillId: string): Promise<any[]> => {
  const manager = getManager();

  const knowledgeMatrizCountQuery = `SELECT count(km.name) AS total, km.name, km.description, km.id FROM knowledge_skill_details ksd 
  INNER JOIN grow_map_knowledge_skill_details gmksd ON ksd.id = gmksd.knowledgeSkillDetailsId
  INNER JOIN knowledge_skill ks ON ks.id = ksd.knowledgeSkillId
  INNER JOIN knowledge_matriz km ON km.id = ksd.knowledgeMatrizId
  WHERE ks.id = '${skillId}'
  GROUP BY km.name`;

  const knowledgeGapsCountQuery = `SELECT COUNT(*) AS total FROM knowledge_gaps_details kgd 
  INNER JOIN grow_map_knowledge_gaps_details gmkgd ON kgd.id = gmkgd.knowledgeGapsDetailsId
  INNER JOIN knowledge_skill ks ON ks.id = kgd.knowledgeSkillId
  WHERE kgd.knowledgeSkillId = '${skillId}'`;

  return Promise.all([
    manager.query(knowledgeMatrizCountQuery),
    manager.query(knowledgeGapsCountQuery),
  ]);
}
Example #22
Source File: ApiApplicationController.ts    From Designer-Server with GNU General Public License v3.0 6 votes vote down vote up
@Post("/{applicationId}/stages")
  @Security("jwt")
  public async postStage(
    @Request() request: exRequest,
    @Path('applicationId') applicationId: number
  ){
    const appRepo = getRepository(Application);
    const findOptions: FindOneOptions = {
      relations: ["stages", "trafficConfigs"],
      where: {
        id: applicationId,
        userId: request.user.id
      }
    }
    
    const app = await appRepo.findOne(findOptions);
    if(!app) { throw new ApplicationError(404, ERROR_CODE.APPLICATION.APPLICATION_NOT_FOUND) }

    const stage = new Stage();
    stage.name = stage.name = `${app.nextVersion}`;
    stage.userId = request.user.id;
    stage.applicationId = app.id;

    await getManager().transaction(async transactionEntityManager => {
      await transactionEntityManager.save(app);
      await transactionEntityManager.save(stage);
    });
    this.setStatus(201);
    return Promise.resolve(stage);
  }
Example #23
Source File: KnowledgeSkill.ts    From liferay-grow with MIT License 6 votes vote down vote up
@Field(() => [User])
  async userGaps(): Promise<User[]> {
    const manager = getManager();

    const knowledgeGapsDetails: any[] = await manager
      .createQueryBuilder('knowledge_gaps_details', 'kgd')
      .innerJoinAndSelect(
        'grow_map_knowledge_gaps_details',
        'gmkgd',
        'gmkgd.knowledgeGapsDetailsId = kgd.id',
      )
      .innerJoinAndSelect('grow_map', 'gm', 'gm.id = gmkgd.growMapId')
      .where('kgd.knowledgeSkill = :id', { id: this.id })
      .execute();

    if (!knowledgeGapsDetails.length) {
      return [];
    }

    const membersId = knowledgeGapsDetails.map(({ gm_userId }) => gm_userId);

    const users = await User.findByIds(membersId, { relations });

    return users;
  }
Example #24
Source File: license-scan-result-item.service.ts    From barista with Apache License 2.0 6 votes vote down vote up
async bomLicensesOnly(
    projectId: number,
    page: number,
    pageSize: number,
    filter: string,
  ): Promise<GetManyDefaultResponse<LicenseDto>> {
    const query = `
          select l.id, l.name, subQ.modulesCount
      from license l,
           (
               select lsri."licenseId", count(*) as modulesCount
               from license_scan_result lsr,
                    license_scan_result_item lsri
               where lsr.id = lsri."licenseScanId"
                 and lsr."scanId" =
                     (select id from scan where "projectId" = $1 and completed_at is not null order by id desc limit 1)
                 and lsri."displayIdentifier" not in
                     (select "licenseItemPath" from bom_license_exception where "projectId" = $1)
               group by lsri."licenseId") subQ
      where l.id = subQ."licenseId"
      and lower(l.name) like $2
      order by l.name`;

    return await PaginateRawQuery<LicenseDto>(
      getManager(),
      query,
      [projectId, '%' + (filter || '').toLowerCase() + '%'],
      page,
      pageSize,
      row =>
        ({
          id: row.id,
          name: row.name,
          modulesCount: row.modulescount,
        } as LicenseDto),
    );
  }
Example #25
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
async function postUserRoleProjectCoachee(wixId: string, pupil: Pupil, info: ApiUserRoleProjectCoachee): Promise<number> {
    if (wixId != pupil.wix_id) {
        logger.warn("Person with id " + pupil.wix_id + " tried to access data from id " + wixId);
        return 403;
    }

    if (pupil.isProjectCoachee) {
        logger.warn("Current user already is a project coachee");
        return 400;
    }

    const entityManager = getManager();

    try {
        pupil.isProjectCoachee = true;
        pupil.projectFields = info.projectFields;
        pupil.isJufoParticipant = info.isJufoParticipant;
        pupil.projectMemberCount = info.projectMemberCount;

        // TODO: transaction log
        await entityManager.save(Pupil, pupil);
    } catch (e) {
        logger.error("Unable to update pupil status: " + e.message);
        return 500;
    }

    return 204;
}
Example #26
Source File: CashTransactionRepository.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async findBestMatch(searchString): Promise<CashTransaction | undefined> {
        const stringQuery = Array.from(
            CashTransactionIndexUtils.generateListItem(searchString),
        ).join(' OR ');

        const cashTransactionIndexRepository = getManager().getCustomRepository(
            CashTransactionIndexRepository,
        );
        const cashTransactionIdQb = cashTransactionIndexRepository
            .createQueryBuilder('cashTransactionIdx')
            .select('rowId')
            .andWhere(`cash_transaction_idx MATCH :stringQuery`)
            .orderBy('rank')
            .limit(1);

        return await this.createQueryBuilder('t')
            .leftJoinAndSelect('t.cashSplitList', 's')
            .leftJoinAndSelect('s.account', 'a')
            .andWhere(`t.id IN ( ${cashTransactionIdQb.getQuery()} )`)
            .setParameter('stringQuery', stringQuery)
            .getOne();
    }
Example #27
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
async function postUserRoleTutor(wixId: string, student: Student, apiTutor: ApiUserRoleTutor): Promise<number> {
    if (wixId != student.wix_id) {
        logger.warn("Person with id " + student.wix_id + " tried to access data from id " + wixId);
        return 403;
    }

    if (student.isStudent) {
        logger.warn("Current user is already a tutor");
        return 400;
    }

    const languages = apiTutor.languages?.map(l => EnumReverseMappings.Language(l)) ?? [];
    if (!languages.every(l => l)) {
        logger.warn(`User wants to set invalid values "${apiTutor.languages}" for languages`);
        return 400;
    }

    const entityManager = getManager();
    //TODO: Implement transactionLog

    try {
        student.isStudent = true;
        student.openMatchRequestCount = 1;
        student.subjects = JSON.stringify(apiTutor.subjects);
        student.supportsInDaZ = apiTutor.supportsInDaz;
        student.languages = languages;
        await becomeTutorScreeningHandler(student, entityManager);
        // TODO: transaction log
        await entityManager.save(Student, student);
    } catch (e) {
        logger.error("Unable to update student status: " + e.message);
        return 500;
    }

    logger.info(`Student ${student.wix_id} became tutor with ${JSON.stringify(apiTutor)}`);
    return 204;
}
Example #28
Source File: CashAccountService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async find(name: string): Promise<CashAccount | undefined> {
        const cashAccountRepository = getManager().getCustomRepository(CashAccountRepository);
        return await cashAccountRepository.findOne({
            where: {
                name,
            },
            relations: ['currency'],
        });
    }
Example #29
Source File: index.ts    From backend with MIT License 6 votes vote down vote up
async function handleUpdateCourseTags(courseTags: { identifier?: string, name?: string }[], courseId: number) {
    const course = await getManager().findOne(Course, { where: { id: courseId } });

    try {
        await course.updateTags(courseTags);
        await getManager().save(course);
        logger.info("Successfully updated course tags");
    } catch (error) {
        logger.warn("Updating course tags failed with ", error.message);
        return 500;
    }

    return 200;
}