How to use the typeorm.getConnection function in typeorm

To help you get started, we’ve selected a few typeorm examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mikesparr / typescript-postgres-auth-example / src / services / flag / goal.dao.ts View on Github external
public save = async (user: User, data: any):
            Promise => {
    if (!user || !data) {
      const message: string = "Required parameters missing";
      throw new MissingParametersException(message);
    }

    const started: number = Date.now();
    const goalRepository: Repository = getConnection().getRepository(Goal);
    const newRecord: CreateGoalDto = data;

    const isOwnerOrMember: boolean = false;
    const action: string = ActivityType.CREATE;
    const permission: AuthPermission = await getPermission(user, isOwnerOrMember, action, this.resource);

    if (permission.granted) {
      try {
        const savedData: Goal = await goalRepository.save(permission.filter(newRecord));

        // log event to central handler
        const ended: number = Date.now();
        event.emit(action, {
          actor: {id: user.id, type: ActorType.Person},
          object: {...savedData, type: ObjectType.Goal},
          resource: this.resource,
github mikesparr / typescript-postgres-auth-example / src / services / authentication / authentication.dao.ts View on Github external
public impersonate = async (
          user: User,
          surrogateUserId: string,
          userAgent: object): Promise => {
    if (!user || !surrogateUserId || !userAgent) {
      const message: string = "Required parameters missing";
      throw new MissingParametersException(message);
    }

    const started: number = Date.now();
    const userRepository: Repository = getConnection().getRepository(User);

    const foundUser: User = await userRepository.findOne(surrogateUserId);
    if (foundUser) {
      const isOwnerOrMember: boolean = false; // TODO: consider logic if manager in group
      const action: string = ActivityType.CREATE;
      const permission: AuthPermission = await getPermission(user, isOwnerOrMember, action, this.surrogateResource);

      if (permission.granted) {
        foundUser.surrogateEnabled = true;
        foundUser.surrogatePrincipal = user;
        const loginUser: User = permission.filter(foundUser);

        return await this.logUserIn(loginUser, userAgent, started);
      } else {
        throw new UserNotAuthorizedException(user.id, action, this.surrogateResource);
      }
github benawad / codeponder / packages / server / src / modules / question / resolver.ts View on Github external
async homeQuestions(
    @Arg("offset", () => Int, { nullable: true }) offset = PAGE_SIZE,
    @Arg("limit", () => Int, { nullable: true, description: "max of 18" })
    limit = PAGE_SIZE
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
  ): Promise {
    if (limit > 18) {
      limit = 18;
    }

    const questions = await getConnection().query(
      `
      select * from code_review_question offset $1 limit $2;
    `,
      [offset, limit]
    );

    return questions;
  }
github hackoregon / openelections / api / models / entity / Activity.ts View on Github external
export async function getActivityByUserAsync(userId, perPage, page: number): Promise {
    const activityRepository = getConnection('default').getRepository('Activity');
    const total = await activityRepository.createQueryBuilder('activity')
        .select('activity.id, "activity"."userId", activity.notes, "activity"."campaignId", "activity"."activityId", "activity"."activityType", "activity"."createdAt", "activity"."attachmentPath"')
        .andWhere('"activity"."userId" = :userId', {userId})
        .getCount();
    const data = await activityRepository.createQueryBuilder('activity')
        .select('activity.id, "activity"."userId", activity.notes, "activity"."campaignId", "activity"."activityId", "activity"."activityType", "activity"."createdAt", "activity"."attachmentPath"')
        .andWhere('"activity"."userId" = :userId', {userId})
        .orderBy('"activity"."createdAt"', 'DESC')
        .limit(perPage)
        .offset(perPage * page)
        .getRawMany() as IActivityResult[];
    return {
        data,
        total,
        perPage,
        page
github secret-tech / backend-ico-dashboard / src / controllers / specs / kyc.controller.spec.ts View on Github external
postRequest(factory.testAppForDashboardWithShuftiproProvider(), '/kyc/callback').send(params).end((err, res) => {
          expect(res.status).to.equal(200);
          getConnection().mongoManager.findOne(ShuftiproKycResult, {signature: params.signature}).then((res) => {
            expect(res.signature).to.equal(params.signature);
            getConnection().mongoManager.findOneById(Investor, new mongo.ObjectId(params.reference)).then(res => {
              expect(res.kycStatus).to.equal(KYC_STATUS_VERIFIED);
              expect(res.kycInitResult).to.deep.equal({
                message: 'message',
                reference: '59f07e23b41f6373f64a8dcb',
                signature: '57b6aa8b377a4818aafa462051d319037a052f5f61ad06c763657674d8063579',
                statusCode: 'SP1',
                timestamp: '2017-11-09T06:47:31.467Z'
              });
              Date.prototype.toISOString = originalToISOString;
              done();
            });
          });
        });
      });
github hackoregon / openelections / api / services / permissionService.ts View on Github external
export async function addUserToCampaignAsync(attrs: IAddUserCampaignAttrs): Promise {
    const userRepository = getConnection('default').getRepository('User');
    const campaignRepository = getConnection('default').getRepository('Campaign');
    const campaign = await campaignRepository.findOneOrFail(attrs.campaignId) as Campaign;
    const currentUser = await userRepository.findOneOrFail(attrs.currentUserId) as User;
    if (await isCampaignAdminAsync(attrs.currentUserId, attrs.campaignId) || await isGovernmentAdminAsync(attrs.currentUserId, campaign.government.id)) {
        let user = await userRepository.findOne({email: attrs.email}) as User;
        if (!user) {
            user = await createUserAsync({
                email: attrs.email,
                firstName: attrs.firstName,
                lastName: attrs.lastName,
            });
            await sendNewUserInvitationEmail({
                to: user.email,
                invitationCode: user.invitationCode,
                campaignName: campaign.name,
            });
            await createActivityRecordAsync({
github hackoregon / openelections / api / services / userService.ts View on Github external
export async function resendInvitationAsync(userId: number): Promise {
    const repository = getConnection('default').getRepository('User');
    const user = await repository.findOneOrFail(userId) as User;
    if (user.userStatus === UserStatus.INVITED && user.invitationCode) {
        await resendInvitationEmail({to: user.email, invitationCode: user.invitationCode});
        await createActivityRecordAsync({
            currentUser: user,
            notes: `${user.name()} was re-sent an invitation email`,
            activityType: ActivityTypeEnum.PERMISSION,
            activityId: user.id
        });
        return true;
    } else {
        throw new Error('User is already in the system or there is no invitation code');
    }
}