Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

beforeUpdate doesn't seem to be called

I have a simple user model as follows :

'use strict';

let hashPassword = (user, options) => {
    if (!user.changed('password')) { return; }
    return require('bcrypt')
        .hash(user.getDataValue('password'), 10)
        .then(hash => user.setDataValue('password', hash));
};

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        username: {allowNull: false, type: DataTypes.STRING, unique: true},
        email: {allowNull: false, type: DataTypes.STRING, unique: true},
        password: {allowNull: false, type: DataTypes.STRING, unique: false},
    }, {
        hooks: {
            beforeCreate: hashPassword,
            beforeUpdate: hashPassword
        }
    });
    return User;
};

It works very well on user creation, but the beforeUpdate hook doesn't seem to work or be called, and the password is saved in plain text in the database.

Where does it come from and how can it be fixed ?

like image 903
Magix Avatar asked Oct 15 '17 18:10

Magix


People also ask

When does the beforeupdate event occur?

The BeforeUpdate event occurs before changed data in a control or record is updated. expression. BeforeUpdate ( Cancel) expression A variable that represents a Form object. The setting determines if the BeforeUpdate event occurs.

How do I cancel the beforeupdate event?

BeforeUpdate ( Cancel) expression A variable that represents a Form object. The setting determines if the BeforeUpdate event occurs. Setting the Cancel argument to True (1) cancels the BeforeUpdate event. Changing data in a control by using Visual Basic or a macro containing the SetValue action doesn't trigger these events for the control.

What are beforeupdate macros and event procedures for a form?

BeforeUpdate macros and event procedures for a form run only if you change the data in one or more controls in the record. For forms, you can use the BeforeUpdate event to cancel updating of a record before moving to another record.

What is beforeupdatemacros and beforeupdateevent in Salesforce?

BeforeUpdatemacros and event procedures for a form run only if you change the data in one or more controls in the record. For forms, you can use the BeforeUpdateevent to cancel updating of a record before moving to another record.


1 Answers

How are you updating the user? There is a difference between getting an instance of the user and updating it and updating by querying the model. The former is an instance update and the latter a bulk update operation (even if your where filter would return a single item).

This distinction is important because beforeUpdate is an instance hook so it would be triggered on instance updates only. You can either change the way you update the user or implement a beforeBulkUpdate hook as well.

like image 184
Unglückspilz Avatar answered Sep 22 '22 09:09

Unglückspilz