DEV Community

Darragh O'Riordan
Darragh O'Riordan

Posted on • Originally published at darraghoriordan.com on

1

Automatically setting empty arrays instead of undefined on typeorm entities

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 = []
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)