TypeORM: Set default value to a selected value from a table

Viewed 703

I have a table named "roles" where I define every roles. It contains two columns "id" which is an uuid and "name" which is an unique role name.

Every time I create an user, I want to set as default value the "user" role, which would be retrieved by its unique name and save his roleId in the "user" table

Here's my code :

export class User extends Common {
  @Column({ name: 'email' })
  email: string;

  @Column({ name: 'first_name' })
  firstName: string;

  @Column({ name: 'last_name' })
  lastName: string;

  @Column({ name: 'password' })
  password: string;

  @Column({ name: 'role_id' })
  roleId: string;

  @OneToMany(() => Role, (role) => role.name)
  @JoinColumn({ name: 'role_id' })
  role: Role;
}

I can't find in the Typeorm's documentation how to set as default a select value where the result matches my condition.

Something like this

@Column({ name: 'role_id', default: Role.findOne({..}).id })
roleId: string;

Is it even possible ?

In case it isn't possible, could I set it by retrieving the Role in a @BeforeInsert operator like this

@BeforeInsert()
public async setDefaultRoleToUser() {
  const role = Role.findOne({ ... });
  this.role = role.id;
}

In case both methods work, which one would be the most optimal ?

Best regards,

0 Answers
Related