About Hooks Classmethods Sequelize

Asked

Viewed 94 times

0

I have a question in the operation of classmethod Hooks etc

I have a model:

const bcrypt = require('bcrypt');
module.exports = (sequelize, DataType) => {

    const User = sequelize.define('tb_users', {
        name: {
            type: DataType.STRING,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        email: {
            type: DataType.STRING,
            allowNull: false,
            unique:true,
            validate: {
                isEmail: true,
                notEmpty: true
            }
        },
        password: {
            type: DataType.STRING,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        }
    },
        {
        hooks:{
            beforeCreate: user => {
                try{
                    const result = User.findAll({
                        where:{
                            name: user.name
                        }
                    });
                    console.log(result);
                    if(result != null){
                        console.log('login já existe');
                    }else{
                        const salt = bcrypt.genSaltSync();
                        user.set('password',bcrypt.hashSync(user.password,salt));
                        console.log(user.password);
                    }
                }catch(error){
                    console.error(error);
                }
            }
        },
        classMethods:{
            isPassword: (encodedPassword, password) => bcrypt.compareSync(password, encodedPassword)   
        }
    });

    return User;
}; 

in my class methods I have this password check, but I have doubt of how I will call it in my controller. Or how this classMethods would work.

1 answer

0

Currently the correct use to instantiate a method in Sequelize is this:

const bcrypt = require('bcrypt');

module.exports = (sequelize, DataType) => {

    const User = sequelize.define('tb_users', {
        ...
    },
        ...
    });

    User.isPassword = (encodedPassword, password) => bcrypt.compareSync(password, encodedPassword) 

    return User;

};

To be called you must use:

if (Users.isPassword(encodedPassword, password)) {
    ...    
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.