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 = [];
    }
  }
}

Hey! Are you a developer?

🚀 Set Up Your Dev Environment in Minutes, Not Hours!

Tired of spending hours setting up a new development machine? I used to be, too—until I automated the entire process!

Now, I just run a single script, grab a coffee, and let my setup take care of itself.

Save 30+ hours configuring a new Mac or Windows (WSL) development environment.
Ensure consistency across all your machines.
Eliminate tedious setup and get coding faster!
Get Instant Access →