question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

@BeforeUpdate not triggered

See original GitHub issue

Issue type:

[ ] question [x] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [ ] postgres [ ] cockroachdb [x] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[ ] latest [ ] @next [x] 0.x.x (0.2.20)

Steps to reproduce or a small repository showing the problem: Seems that @BeforeUpdate is not triggered. We are using CrudController and TypeOrmCrudService from @nestjsx also.

Contact model:

import { Entity, Column, OneToMany, ManyToOne, JoinColumn, BeforeInsert, BeforeUpdate, AfterUpdate } from 'typeorm'
import { ApiModelProperty } from '@nestjs/swagger'
import {
    IsString,
    IsEmail,
    IsPhoneNumber,
    ValidateIf,
} from 'class-validator'
import { PhoneNumberUtil, PhoneNumber, PhoneNumberFormat } from 'google-libphonenumber'
import { BaseEntity } from './base.entity'
import { Lead } from './lead.entity';
import { Person } from './person.entity';

@Entity({
    name: 'contacts',
})
export class Contact extends BaseEntity {
    @ApiModelProperty({
        description: 'Contact email',
        type: 'string',
        required: false,
        example: 'email@domain.com',
    })
    @ValidateIf(o => {
        if (o.email === undefined && o.phoneNumber !== undefined) {
            return false
        }

        return true
    })
    @IsString()
    @IsEmail()
    @Column({ length: 255, nullable: true })
    email: string

    @ApiModelProperty({
        description: 'Contact Phone number',
        type: 'string',
        required: false,
        example: '+393334456789',
    })
    @ValidateIf(o => {
        if (o.phoneNumber === undefined && o.email !== undefined) {
            return false
        }

        return true
    })
    @IsString()
    @IsPhoneNumber(null)
    @Column({ name: 'phone_number', length: 255, nullable: true })
    phoneNumber: string

    @ApiModelProperty({
        description: 'Person join column',
        type: type => Person,
        required: false,
        readOnly: true,
    })
    @ManyToOne(type => Person, person => person.contacts)
    @JoinColumn()
    person: Person

    @ApiModelProperty({
        description: 'Person Id',
        required: false,
        type: 'string',
        example: 'd49416ea-ace6-57aa-bce7-345d7716bfe5',
    })
    @Column({ nullable: true })
    personId: string

    @ApiModelProperty({
        description: 'Leads join column',
        type: type => Lead,
        required: false,
        isArray: true,
        readOnly: true,
    })
    @OneToMany(type => Lead, lead => lead.contact)
    @JoinColumn()
    leads: Lead[]

    @BeforeUpdate()
    entityFormatPhoneNumber() {
        console.log("entityFormatPhoneNumber()")
        if (this.phoneNumber !== undefined && this.phoneNumber !== null) {

            const instance = PhoneNumberUtil.getInstance()

            try {
                const phoneNumberParsed: PhoneNumber = instance.parse(this.phoneNumber)

                const value: string = instance.format(phoneNumberParsed, PhoneNumberFormat.E164)

                this.phoneNumber = value

            } catch (err) {
                console.log("entityFormatPhoneNumber()->error", err);
            }
        }
    }
}

Let me know if you need further informations.

Thank you, Mattia

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:8
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

7reactions
aalaunocommented, Feb 6, 2022

I had the same problem and found solution

it works with .save() method instead of spread just use Object.assign() Example:

const foundEntity = await this.repository.findOne(id);
const updatedEntity = await this.repository.save(Object.assign(foundEntity, updates));

then, @BeforeUpdate works

3reactions
nelsonfleigcommented, Jan 16, 2022

So I found that updating the entity using the spread operator also doesn’t trigger the BeforeUpdate hook. You need to update the values of the entity returned by the .find() method directly.

This doesn’t work:

const foundEntity = await this.repository.findOne(id);
const updatedEntity = {...foundEntity, ...updateData};
await this.respository.save(updatedEntity);

But this works:

const foundEntity = await this.repository.findOne(id);
Object.entries(updateData).forEach(([key, value]) => {
  foundEntity[key] = value;
});
await this.respository.save(foundEntity);

I was stuck for a while on this. Hope it helps anyone.

Read more comments on GitHub >

github_iconTop Results From Across the Web

why sequelize beforeUpdate hook doesn't work?
Turn out, that the @BeforeUpdate hook is triggered, when you first find a single record and then update it: await Model.
Read more >
beforeUpdate not called when updated via model where. #6253
Hi. I'm trying to to hash a password before updating an object. model: module.exports = function (sequelize, DataTypes) { var User ...
Read more >
Before update trigger is not working
Looks like you aren't updating the records in trigger.new in your update branch, which could be your problem. I'd advise others to hold...
Read more >
Form.BeforeUpdate event (Access) - Microsoft Learn
The BeforeUpdate event is triggered when a control or record is updated. Within a record, changed data in each control is updated when...
Read more >
Vue 3 lifecycle hooks with real-time example - Canopas
Note that beforeUpdate will not be directly called on page loading, it will be only executed if you update something in DOM. The...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found