Automatically setting empty arrays instead of undefined on typeorm entities

Photo by Sergi Kabrera on Unsplash

If you have an array on an entity model in typeorm you will have to handle the response when there are no items available to put in the array.

In my application I return the entity model directly for GET requests and I like having arrays as empty instead of undefined properties.

By default typeorm will not set the property to [] so it will be undefined.

Here is how to set an array property to have an empty array instead of undefined.

Using type ORM After hooks

Type ORM has a number of hooks available that let us modify the model after certain actions.

The actions we care about are @AfterLoad(), @AfterInsert(), @AfterUpdate().

To use them you decorate an async method with the action you want run when typeorm has completed the hook.

e.g.

@Entity()
export class CustomBot {
  @PrimaryGeneratedColumn()
  @ApiProperty()
  public id!: number;

  @Type(() => Trigger)
  @OneToMany(() => Trigger, (trigger) => trigger.customBot, {
    onDelete: "CASCADE",
  })
  @ApiProperty({ isArray: true, type: () => Trigger })
  @ValidateNested({ each: true })
  triggers!: Trigger[];

  // eslint-disable-next-line @typescript-eslint/require-await
  @AfterLoad()
  @AfterInsert()
  @AfterUpdate()
  async nullChecks() {
    if (!this.triggers) {
      this.triggers = [];
    }
  }
}