Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instance Methods and Hooks not working #8030

Closed
vidur149 opened this issue Jul 29, 2017 · 7 comments
Closed

Instance Methods and Hooks not working #8030

vidur149 opened this issue Jul 29, 2017 · 7 comments

Comments

@vidur149
Copy link

What you are doing?

I am trying to access an instance method. Also the before create instance hook doesnt work.
As you can see the hashed password is geeting generated but unhashed password goes into the database.
model.ts

let User: UserModel = sequelize.define<UserInstance, UserAttribute>('user', {
        id: {
            type: Sequelize.INTEGER(11),
            primaryKey: true,
            autoIncrement: true,
            allowNull: false,
        },
        name: {
            type: Sequelize.STRING(150),
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        email: {
            type: Sequelize.STRING(50),
            allowNull: false,
            validate: {
                notEmpty: true,
                isEmail: true
            }
        },
        role: {
            type: Sequelize.ENUM('god', 'jesus', 'romans'),
            allowNull: false,
            validate: {
                notEmpty: true,
            },
            defaultValue: 'romans'
        },
        password: {
            type: Sequelize.STRING(50),
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        status: {
            type: Sequelize.ENUM('active', 'inactive', 'deleted'),
            allowNull: false,
            defaultValue: 'active',
            validate: {
                notEmpty: true
            }
        },
        emailNotif: {
            type: Sequelize.BOOLEAN,
            allowNull: false,
            defaultValue: false
        },
        pushNotif: {
            type: Sequelize.ENUM('disable', 'morning', 'night', 'day'),
            allowNull: false,
            defaultValue: 'disable'
        },
        deleteOn: {
            type: Sequelize.DATE,
            allowNull: true
        }
    }, {
            classMethods: {
                associate: (models) => { }
            },
            instanceMethods: {
                hashPassword: function(password) {
                    bcrypt.hash(password, 8, (err, hash) => {
                        return password;
                    });
                },
                callMe: function() {
                    console.log('hey');
                }
            },
            hooks: {
                beforeUpdate: (user: UserInstance, options: Object) => {
                    console.log(user.password);
                    bcrypt.hash(user.password, 8, (err, hash) => {
                        user.password = hash;
                        console.log(user.password);
                        // user.password = hash;
                    });
                },
            }
        });
        
    return User;

controller.ts

this.database.user.create(request.payload).then((user) => {
            user.callMe();
            return reply({
                "success": true
            });
        });

What do you expect to happen?

I exepcted that the callMe function will be called.

What is actually happening?

image

Dialect: mysql
Database version: XXX
Sequelize version: 4.42

@eseliger
Copy link
Member

Instance and class methods have been removed as of v4. See here
Also, your beforeUpdate hook updates the user asynchronously. You should return a promise so sequelize knows it has to wait for your hook to finish doing its task and updating the user.

@vidur149
Copy link
Author

The associate key won't work as well?

@FrenchBully
Copy link

FrenchBully commented Jul 31, 2017

@vidur149 should look like:

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

// Class Method
Model.associate = function (models) {
    ...associate the models
};

// Instance Method
Model.prototype.someMethod = function () {..}

@RishabhVerma
Copy link

@FrenchBully Thanks.

@vidur149
Copy link
Author

vidur149 commented Aug 2, 2017

@FrenchBully Thanks 👍

@vidur149 vidur149 closed this as completed Aug 2, 2017
@Stiveknx
Copy link

Stiveknx commented Apr 16, 2018

I'm getting issues with it too.

I've tried to create an instance, just like @FrenchBully said, but whenever I try to use it says "db.my_model.my_instance is not a function".

let Alunos = <alunosModel> sequelize.define('alunos', { /* all defines here */ });

Alunos.prototype.fullProfile =  function (id) {
        return new Promise((resolve, reject) => {
            let find = <alunosFull> db.alunos.findOne({
                where: {'id': id},
                attributes: ['nome', 'sexo', 'email', 'senha', 'numeroUnico', 'foto', 'nivel', 'serie', 'periodo'],
                include: [{
                    model: db.cupom,
                    attributes: ['limite_duvida', 'qtd_usada', 'qtd_aluno', 'credenciado_id']
                }]
            });
            resolve(<alunosFull> find);
        });
    };
let alunos_full = await <alunosFull>db.alunos.fullProfile(user);
TypeError: models_1.db.alunos.fullProfile is not a function

@Stiveknx
Copy link

Well, I've just changed the instance method for an class method and worked!

Alunos.prototype.fullProfile =  function (id) {} 

By:

Alunos.fullProfile =  function (id) { }

I just really didn't got why, I think the instance method should have worked ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants