Reputation: 203
I have just coding the todolist api project on NodeJS & Express. I follow some instruction using Sequelize to interact with DB: SQLite. But I encounter with Sequelize to create class method as below:
user.js
var bcrypt = require('bcrypt');
var _ = require('underscore');
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('user', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
salt: {
type: DataTypes.STRING
},
password_hash: {
type: DataTypes.STRING
},
password: {
type: DataTypes.VIRTUAL,
allowNull: false,
validate: {
len: [6, 100]
},
set: function (value) {
var salt = bcrypt.genSaltSync(10);
var hashedPassword = bcrypt.hashSync(value, salt);
this.setDataValue('password', value);
this.setDataValue('salt', salt);
this.setDataValue('password_hash', hashedPassword);
}
}
}, {
hooks: {
beforeValidate: (user, options) => {
if (typeof user.email === 'string') {
user.email = user.email.toLowerCase();
}
}
}
});
return User;
// Class methods
User.prototype.toPublicJSON = function() {
var json = this.toJSON();
return _.pick(json, 'id', 'email', 'createdAt', 'updatedAt');
};
User.authenticate = (body) => {
return new Promise ((resolve, reject) => {
if (typeof body.email !== 'string' || typeof body.password !== 'string') {
return reject();
}
user.findOne({
where: {
email: body.email
}
}).then((user) => {
if (!user || !bcrypt.compareSync(body.password, user.get('password_hash'))) {
return reject();
}
resolve(user);
}, (e) => {
reject();
})
});
};
}
db.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize(undefined, undefined, undefined, {
'dialect': 'sqlite',
'storage': __dirname + '/data/dev-todo-api.sqlite'
});
db = {};
db.todo = sequelize.import(__dirname + '/models/todo.js');
db.user = sequelize.import(__dirname + '/models/user.js');
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
user.js
app.post('/users/login', (req, res) => {
var body = _.pick(req.body, 'email', 'password');
db.user.authenticate(body).then((user) => {
res.json(user.toPublicJSON());
}, () => {
res.status(401).send();
});
})
Error: db.user.authenticate is not function.
I think I can use function authenticate after user.js return variable User. Please advise me how to resolve this problem. Thanks all.
Upvotes: 0
Views: 304
Reputation: 1955
The problem is not with sequelize
. Rather you are defining the methods after return, so the code that is responsible for creating the methods is never reached.
return User;
// Class methods
User.prototype.toPublicJSON = function() {
var json = this.toJSON();
return _.pick(json, 'id', 'email', 'createdAt', 'updatedAt');
};
User.authenticate = (body) => {
You should move the return User
statement at the end of your arrow function and your code should work.
Upvotes: 1