How to use typeorm - 10 common examples

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 sogehige / sogeBot / test / helpers / db.js View on Github external
await transactionalEntityManager.query('SET FOREIGN_KEY_CHECKS=0;');
          }
          for (const metadata of metadatas) {
            if (['mysql'].includes((await getManager()).connection.options.type)) {
              await transactionalEntityManager.query(`TRUNCATE TABLE ${metadata.tableName}`);
            } else {
              await transactionalEntityManager.query(`TRUNCATE "${metadata.tableName}" CASCADE`);
            }
          }
          if (['mysql'].includes((await getManager()).connection.options.type)) {
            await transactionalEntityManager.query('SET FOREIGN_KEY_CHECKS=1;');
          }
        });
      } else {
        for (const entity of entities) {
          await getRepository(entity).clear();
        }
      }

      debug('test', chalk.bgRed('*** Cleaned successfully ***'));

      await permissions.ensurePreservedPermissionsInDb(); // re-do core permissions

      oauth.generalChannel = 'soge__';
      oauth.generalOwners = ['soge__', '__owner__'];
      oauth.broadcasterUsername = 'broadcaster';
      oauth.botUsername = 'bot';
      oauth.botId = '12345';

      oauth.broadcasterId = '54321';
      tmi.ignorelist = [];
github bradymholt / koa-vuejs-template / api / db / Initializer.ts View on Github external
static async init(
    connectionOptions: PostgresConnectionOptions,
    seed: boolean = false
  ) {
    // Get the options and clone to a new object since node-config gives a read-only object and TypeORM attempts to modify it.
    let options: any = Object.assign({}, connectionOptions);
    // Prepend absolute path to entities/migrations items
    options.entities = options.entities.map(item => {
      return `${__dirname}/../${item}`;
    });
    options.migrations = options.migrations.map(item => {
      return `${__dirname}/../${item}`;
    });

    try {
      let connection = await createDbConnection(options as ConnectionOptions);
      if (seed) {
        console.log("Seeding the database...");
        await this.seedData();
      }
    } catch (err) {
      console.log(`Error initializing the database: ${err}`);
      throw err;
    }
  }
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 ShipChain / engine / RunMigrations.ts View on Github external
const defaultOptions = await getConnectionOptions();
            const rdsOptions = await getRDSconfig();

            const fullOptions = Object.assign(
                {},
                defaultOptions,
                rdsOptions,
                {
                    subscribers: [],
                    synchronize: false,
                    migrationsRun: false,
                    dropSchema: false,
                    logging: ["query", "error", "schema"]
                });

            connection = await createConnection(fullOptions);

            const options = { transaction: true };
            await connection.runMigrations(options);
            await connection.close();

            // exit process if no errors
            process.exit(0);

        } catch (err) {
            if (connection) await (connection as Connection).close();

            logger.error(`Error during migration run: ${err}`);
            process.exit(1);
        }
    }
}
github chnirt / nestjs-graphql-best-practice / src / resolvers / user.resolver.ts View on Github external
async verifyEmail(@Args('emailToken') emailToken: string): Promise {
		const user = await verifyEmailToken(emailToken)

		// console.log(user)

		if (!user.isVerified) {
			const updateUser = await getMongoRepository(User).save(
				new User({
					...user,
					isVerified: true,
				})
			)
			return updateUser ? true : false
		} else {
			throw new ForbiddenError('Your email has been verified.')
		}
	}
github chnirt / nestjs-graphql-best-practice / src / resolvers / user.resolver.ts View on Github external
async changePassword(
		@Args('_id') _id: string,
		@Args('currentPassword') currentPassword: string,
		@Args('password') password: string
	): Promise {
		const user = await getMongoRepository(User).findOne({ _id })

		// console.log(currentPassword , password)

		if (!user) {
			throw new ForbiddenError('User not found.')
		}

		if (!(await comparePassword(currentPassword, user.local.password))) {
			throw new ForbiddenError('Your current password is missing or incorrect.')
		}

		if (await comparePassword(password, user.local.password)) {
			throw new ForbiddenError(
				'Your new password must be different from your previous password.'
			)
		}
github magishift / magishift.core / src / crud / crud.service.ts View on Github external
if (filter.where) {
      const whereStrings = this.queryWhereBuilder(filter.where, tableName);
      if (whereStrings.length > 0) {
        whereStrings.map(whereString => {
          if (whereString) {
            query.andWhere(whereString);
          }
        });
      }
    }

    if (filter.whereOr) {
      const whereStringOrs = this.queryWhereBuilder(filter.whereOr, tableName);
      if (whereStringOrs.length > 0) {
        query.andWhere(
          new Brackets(qb => {
            whereStringOrs.map(whereStringOr => {
              if (whereStringOr) {
                qb.orWhere(whereStringOr);
              }
            });
          }),
        );
      }
    }

    // resolve order by
    if (filter.order && filter.order.length > 0) {
      let isNewOrder: boolean = true;

      filter.order.forEach(val => {
        const split = val.split(' ');
github hanpama / girin / packages / app-typeorm / src / TypeORMFrameworkDatastore.ts View on Github external
protected formatPredicate(entityType: Function, predicate: { [field: string]: any }): Brackets {
    // field names should be alphanumeric
    const predicateFieldPatt = /^[\w\d]+$/;

    const predciateFields = Object.keys(predicate);
    const condition: { fieldName: string, value: any }[] = [];
    for (let i = 0; i < predciateFields.length; i++) {
      const fieldName = predciateFields[i];

      if (!predicateFieldPatt.test(fieldName)) {
        throw new Error('Invalid field name');
      }
      condition.push({ fieldName, value: predicate[fieldName] });
    }

    return new Brackets(qb => {
      condition.forEach(({ fieldName, value }) => qb.andWhere(
        `${fieldName} = :${fieldName}`,
        { [fieldName]: value },
      ));
    });
  }
github mpcast / mpcast-server / packages / core / src / service / services / categories.service.ts View on Github external
.where('obj.type = :type', { type: 'page' })
      .andWhere(where)
      // .andWhere('obj.status IN (:status)', { status: 'publish' })
      .andWhere('t.slug = :categorySlug', { categorySlug })
      .orderBy('obj.updatedAt', 'DESC')
      .offset(page)
      .limit(pageSize)
      .getRawMany();
    // 以下处理元数据
    const objIds: ID[] = [];
    data.forEach(item => {
      objIds.push(item.id);
    });
    if (!_.isEmpty(objIds)) {
      const metaData = await this.connection.getRepository(PostMeta).find({
        post: In(objIds),
      });
      data.forEach(item => {
        item.metas = _.filter(metaData, { id: item.id });
      });
    }
    return data;
  }
github xpioneer / koa-graphql-typescript / src / controllers / ArticleController.ts View on Github external
static async pages(args: any) {
    console.log(args, 'query args ===================')
    const options: FindManyOptions<article> = {
      skip: args.page &lt; 2 ? 0 : (args.page - 1) * args.pageSize,
      take: args.pageSize,
      order: {},
      where: {
        deletedAt: null
      }
    }
    if(args.title) {
      options.where['title'] = Like(`%${args.title}%`)
    }
    if(args.abstract) {
      options.where['abstract'] = Like(`%${args.abstract}%`)
    }
    if(args.tag) {
      options.where['tag'] = Like(`%${args.tag}%`)
    }
    if(args.createdAt) {
      const date = args.createdAt.map((c: string) =&gt; (Moment(c)).valueOf())
      options.where['createdAt'] = Between(date[0], date[1])
    }
    if(args.order) {
      options.order = Object.assign(options.order, args.order)
    }
    console.log(options, '----options')

    const pages = await getRepository(Article).findAndCount(options)
      // .createQueryBuilder()
      // .where({</article>