How to use the typeorm.BeforeInsert 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 goldcaddy77 / warthog / src / core / BaseModel.ts View on Github external
@Column({ nullable: true })
  updatedById?: IDType;

  @Column({ nullable: true })
  deletedAt?: Date;
  @Column({ nullable: true })
  deletedById?: IDType;

  @VersionColumn() version!: number;

  getId() {
    // If settings allow ID to be specified on create, use the specified ID
    return this.id || shortid.generate();
  }

  @BeforeInsert()
  setId() {
    this.id = this.getId();
  }
}

// This class adds all of the TypeORM decorators needed to create the DB table
@ObjectType({ implements: BaseGraphQLObject })
export abstract class BaseModelUUID implements BaseGraphQLObject {
  @PrimaryGeneratedColumn('uuid')
  id!: IDType;

  @CreateDateColumn() createdAt!: Date;
  @Column() createdById!: IDType;

  @UpdateDateColumn({ nullable: true })
  updatedAt?: Date;
github ZhiXiao-Lin / nestify / server / src / common / entities / content.entity.ts View on Github external
static create(target: object): Content | Content[] {
        return plainToClass(Content, target);
    }

    @Expose()
    get thumbnailPath(): string {
        return Base.getFullPath(this.thumbnail);
    }

    @Expose()
    get videoPath(): string {
        return Base.getFullPath(this.video);
    }

    @BeforeInsert()
    async beforeInsert() {
        if (!this.publish_at) {
            this.publish_at = moment().format('YYYY-MM-DD HH:mm:ss');
        }
        const text = extractionTextInHtml(this.text);
        this.summary = textInterception(text, 120);
    }

    @BeforeUpdate()
    async beforeUpdate() {
        const text = extractionTextInHtml(this.text);
        this.summary = textInterception(text, 120);
    }

    // @AfterInsert()
    // async afterInsert() {
github hackoregon / openelections / api / models / entity / Campaign.ts View on Github external
@OneToMany(type => Activity, activity => activity.user)
    activities: Activity[];

    @OneToMany(type => Permission, permission => permission.campaign)
    permissions: Permission[];

    @OneToMany(type => Contribution, contribution => contribution.government)
    contributions: Contribution[];

    @OneToMany(type => Expenditure, expenditure => expenditure.government)
    expenditures: Expenditure[];

    public errors: ValidationError[];

    @BeforeInsert()
    @BeforeUpdate()
    async validate() {
        await this.validateAsync();
        if (this.errors.length > 0) {
            throw new Error('campaign has one or more validation problems');
        }
    }

    async isValidAsync(): Promise {
        await this.validateAsync();
        return this.errors.length === 0;
    }

    async validateAsync() {
        const errors = await validate(this);
        this.errors = errors;
github nomadcoders / nuber-server / src / entities / Verification.ts View on Github external
target: verificationTarget;

  @Column({ type: "text" })
  payload: string;

  @Column({ type: "text" })
  key: string;

  @Column({ type: "boolean", default: false })
  verified: boolean;

  @CreateDateColumn() createdAt: string;

  @UpdateDateColumn() updatedAt: string;

  @BeforeInsert()
  createKey(): void {
    if (this.target === PHONE) {
      this.key = Math.floor(Math.random() * 100000).toString();
    } else if (this.target === EMAIL) {
      this.key = Math.random()
        .toString(36)
        .substr(2);
    }
  }
}
export default Verification;
github chnirt / nestjs-graphql-best-practice / src / models / file.entity.ts View on Github external
@Column()
	filename: string

	@Column()
	path: string

	@Column()
	createdAt: number
	@Column()
	updatedAt: number

	constructor(file: Partial) {
		Object.assign(this, file)
	}

	@BeforeInsert()
	save() {
		this._id = uuid.v1()
		this.createdAt = +new Date()
		this.updatedAt = +new Date()
	}

	@BeforeUpdate()
	update() {
		this.updatedAt = +new Date()
	}
}
github chnirt / nestjs-graphql-best-practice / src / models / history.entity.ts View on Github external
_id: string

	@Column()
	@IsString()
	userId: string

	@Column()
	@IsString()
	description: string

	@CreateDateColumn()
	createdAt: string
	@UpdateDateColumn()
	updatedAt: string

	@BeforeInsert()
	save() {
		this._id = uuid.v1()
	}
}
github rucken / todo-nestjs / libs / rucken / todo-nestjs / src / migrations_entities / 1552133567377 / task.entity.ts View on Github external
@Type(() => Status1552133567377)
  @ManyToOne(type => Status1552133567377, { eager: true, nullable: true })
  @JoinColumn({ name: 'status_id' })
  status: Status1552133567377 = undefined;

  @Type(() => User1524199022084)
  @ManyToOne(type => User1524199022084, { eager: true, nullable: true })
  @JoinColumn({ name: 'created_user_id' })
  createdUser: User1524199022084 = undefined;

  @Type(() => User1524199022084)
  @ManyToOne(type => User1524199022084, { eager: true, nullable: true })
  @JoinColumn({ name: 'updated_user_id' })
  updatedUser: User1524199022084 = undefined;

  @BeforeInsert()
  doBeforeInsertion() {
    const errors = validateSync(this, { validationError: { target: false } });
    if (errors.length > 0) {
      throw new CustomValidationError(errors);
    }
  }

  @BeforeUpdate()
  doBeforeUpdate() {
    const errors = validateSync(this, { validationError: { target: false } });
    if (errors.length > 0) {
      throw new CustomValidationError(errors);
    }
  }
}
github danielwii / asuna-node-server / src / modules / core / base / base.entity.ts View on Github external
createdAt?: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt?: Date;

  @MetaInfo({ accessible: 'hidden' })
  @Column({ nullable: true, length: 100, name: 'updated_by' })
  updatedBy?: string;

  constructor(idPrefix: string = '') {
    super();
    this.idPrefix = idPrefix;
    this.generator = new SimpleIdGenerator(idPrefix);
  }

  @BeforeInsert()
  beforeInsert(): void {
    this.id = this.generator.nextId();
  }

  @AfterLoad()
  afterLoad(): void {
    this.createdAt = DateTime.fromJSDate(this.createdAt)
      .plus(Duration.fromObject({ hours: 8 }))
      .toJSDate();
    this.updatedAt = DateTime.fromJSDate(this.updatedAt)
      .plus(Duration.fromObject({ hours: 8 }))
      .toJSDate();
  }
}

export class AbstractTimeBasedNameEntity extends AbstractTimeBasedBaseEntity {
github penta-jelly / re-radio / server / src / radio / song / entities / song.entity.ts View on Github external
@ManyToOne(
    type => Station,
    station => station.songs,
  )
  station: Station;

  @Column()
  stationSlug: string;

  @Column('int', { array: true, default: '{}' })
  upVoteUserIds: number[];

  @Column('int', { array: true, default: '{}' })
  downVoteUserIds: number[];

  @BeforeInsert()
  @BeforeUpdate()
  private updateStationSlug() {
    if (this.station) {
      this.stationSlug = this.station.slug;
    }
  }
}
github chnirt / nestjs-graphql-best-practice / src / models / permission.entity.ts View on Github external
_id: string

	@Column()
	@IsString()
	code: string

	@Column()
	@IsString()
	description: string

	@CreateDateColumn()
	createdAt: string
	@UpdateDateColumn()
	updatedAt: string

	@BeforeInsert()
	save() {
		this._id = uuid.v1()
	}
}