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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more