#BeforeUpdate hook not triggering

3 messages · Page 1 of 1 (latest)

buoyant moth
#

Here is an example of the issue that occurs sometimes and I still don't know why.

All you need to care about is order_year, and BeforeUpdate hook

Entity:

@Entity('order')
    @Index('UQ_ORDER_NUMBER_YEAR', ['order_year', 'order_number'], { unique: true })
    @ObjectType()
    export class Order extends BaseUUIDEntity {
      @Field(() => Int, { nullable: false })
      @Column({ type: 'text' })
      order_number!: number;
    
    
      @Field(() => Date, { nullable: false })
      @Column({ type: 'timestamp' })
      order_date!: Date;
    
    
      @Field({ nullable: false })
      @Column({ type: 'text' })
      order_year!: string;
    
    
      @Field(() => Customer, { nullable: false })
      @ManyToOne(() => Customer, { lazy: true })
      customer!: Customer;
    
      @BeforeInsert()
      @BeforeUpdate()
      setOrderYear() {
        this.order_year = new Date(this.order_date).getFullYear().toString();
      }
    }

Repository:

async updateOrder(
    { id, ...order }: UpdateOrderDto,
    entityManager?: EntityManager,
  ): Promise<Order> {
    try {
      const manager = this.getManager(entityManager);

      await manager.update(Order, id, order);
      return manager.findOne(Order, {
        where: { id },
      }) as Promise<Order>;
    } catch (error) {
      throw this.handleDatabaseError(error);
    }
  }

I make a request which triggers the update method.
Here is what the data looks like before the update:

{
  "order_date": "2025-05-10T10:53:23.619Z",
  "order_year": "2025"
}

Here is after updating:

{
"order_date": "2010-05-10T10:53:23.619Z",
 "order_year": "2025"
}```

The hook never triggers

I know there are better ways to modify the value of order_year, but that isn't why I'm here, I want to know why the hook does not trigger.
fervent grove
#

looks like the reason ur @BeforeUpdate hook never triggers is cuz of how TypeORM handles direct update operation

buoyant moth
#

I fixed it by doing this