0

Can someone help me figure out how to use my sequelize instance methods on my controller?

I wrote my model like that:

const bcrypt = require('bcryptjs');

module.exports = (sequelize, Sequelize) => {
  const Patient = sequelize.define('Patient', {
    email: { 
      type: Sequelize.STRING,
      allowNull: false,
    },
    password : { 
      type: Sequelize.STRING,
      allowNull: false,
    },
  }, {
    classMethods: {
      associate: (models) => {
        // associations can be defined here
      }
    },
    instanceMethods: {
      generateHash: function (password) {
                  return bcrypt.hash(password, 8, function(err, hash){
                      if(err){
                          console.log('error'+err)
                      }else{
                          return hash;
                      }
                  });
              },
      validPassword: function(password) {
          return bcrypt.compareSync(password, this.password);
      }        
    }
  });
  return Patient;
};

but when I launch it on my controller which I made like that

const jwt = require('jsonwebtoken');
const passport = require('passport');
const Patient = require('../models').Patient;

module.exports = {
///
  create(req, res) {
    return Patient
      .create({
        email: req.body.email,
        password: Patient.prototype.generateHash(req.body.password)
      })
      .then(patient => res.status(201).send(patient))
      .catch(error => res.status(400).send(error));
  },
};

I get this error for the request:

TypeError: Cannot read property 'generateHash' of undefined

1 Answer 1

1

First of all you should use bcrypt.hashSync() because you want to assign asynchronous function call to the password - it won't work.

generateHash: function(password){
    try {
        return bcrypt.hashSync(password, 8);
    } catch (e) {
        console.log('error: ' + e);
    }
}

In order to use instance method you should do

Patient.build().generateHash(req.body.password);

build() creates new instance of model so then you can run the instance method. Or you can declare the generateHash as a class method so you could run it like that

Patient.generateHash(req.body.password);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.