Automatically setting empty arrays instead of undefined on typeorm entities

Published on October 19, 2021

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

Hi! I'm Darragh ORiordan.

I live and work in Sydney, Australia building and supporting happy teams that create high quality software for the web.

I also make tools for busy developers! Do you have a new M1 Mac to setup? Have you ever spent a week getting your dev environment just right?

My Universal DevShell tooling will save you 30+ hours of configuring your Windows or Mac dev environment with all the best, modern shell and dev tools.

Get DevShell here: ✨ https://usemiller.dev/dev-shell


Read more articles like this one...

List of article summaries

#nestjs

A Nest JS Pipeline Cheatsheet

I’m always checking the NestJS documentation to read what a Middleware Vs Interceptor is and I could never remember the order that the different NestJS pipeline elements are called in.

So I made this cheatsheet for myself so I had something to refer to.

#nestjs

Using a dynamic DTO property in a NestJS API

NestJS is designed around using strictly typed properties on models but sometimes it’s useful (and fast!) to allow dynamic types on properties and just store some business domain data as a dynamic serialized blob.

This is the serialized LOB method recommended by Martin Fowler (https://martinfowler.com/eaaCatalog/serializedLOB.html).

Here is how you can have a LOB in a NestJS REST Api with type safety and support for OpenAPI definitions.

#nestjs

Fixing validation error in NestJS when using forbidUnknwonValues

If you get unexplained validation errors (http status 400) when calling a NestJS api you might want to check your Query() parameters. Parsing and validating these the wrong way can cause issues.

Comments