Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize classMethods vs instanceMethods

So starting my adventure into all things Node. One of the tools I am trying to learn is Sequelize. So I will start off what I was trying to do:

'use strict';
var crypto = require('crypto');

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    username: DataTypes.STRING,
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    salt: DataTypes.STRING,
    hashed_pwd: DataTypes.STRING
  }, {
    classMethods: {

    },
    instanceMethods: {
      createSalt: function() {
        return crypto.randomBytes(128).toString('base64');
      },
      hashPassword: function(salt, pwd) {
        var hmac = crypto.createHmac('sha1', salt);

        return hmac.update(pwd).digest('hex');
      },
      authenticate: function(passwordToMatch) {
        return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;
      }
    }
  });
  return User;
};

I am confused on when to use classMethods vs instanceMethods. To me when I think about createSalt() and hashPassword() should be class methods. They are general and for the most part dont really have anything to do with the specific instance they are just used in general. But when I have createSalt() and hashPassword() in classMethods I cannot call them from instanceMethods.

I have tried variations of the following:

this.createSalt();
this.classMethods.createSalt();
createSalt();

Something like below wont work and I am probably just not understanding something simple.

authenticate: function(passwordToMatch) {
  console.log(this.createSalt());
  return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;
}

Any hints/tips/direction would be very much so appreciated!

like image 761
Silent Avatar asked Dec 14 '15 02:12

Silent


1 Answers

All the method who don't modify or check any type of instance should be classMethod and the rest instanceMethod

ex:

// Should be a classMethods
function getMyFriends() {
  return this.find({where{...}})
}

// Should be a instanceMethods
function checkMyName() {
  return this.name === "george";
}
like image 143
NBeydon Avatar answered Sep 25 '22 11:09

NBeydon