Entity mapping

Let's map our user entity to a database table.

We can return to the user.entity file, where we'll map our entity to the database using TypeORM decorators.

Begin by marking the class itself with @Entity(), indicating that it should be a table. After that, we can mark the id attribute with @PrimaryGeneratedColumn(), indicating that it is the primary column and also serial (auto-increment). Finally, we can mark the remaining attributes with @Column() to indicate that they are normal columns. As they are all of type string, they will by default be mapped to VARCHAR.

Finally, let's also create an options object inside the @Column() decorator over the email and phone attributes to enable the unique option, as every user should have a unique email and phone. Our current result should look like this

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;

  @Column({ unique: true })
  phone: string;

  @Column()
  password: string;
}

We'll also create Date columns to register when an entity was created or last updated. As this will be a recurring pattern, we'll use an embedded entity to represent this data and avoid repetition. So, let's create the file common -> embedded -> registry-dates.embedded with the following

export class RegistryDates {
  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

Finally, we can apply it in our User class as an embedded entity.

@Column(() => RegistryDates, { prefix: false })
registryDates: RegistryDates;

Disabling the prefix option avoids altering the fields' names when fetching.

Commit - Mapping user entity to database table

Last updated