$ npm install --save bcryptjs
'use strict';
const {
Model
} = require('sequelize');
const bcryptjs = require('bcryptjs');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
User.init({
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: { msg: "必須填寫" },
notEmpty: { msg: "不能為空字符串" },
isEmail: { msg: "格式不正確" },
async isUnique(value) {
const user = await User.findOne({ where: { email: value } })
if (user) {
throw new Error("郵箱已存在");
}
}
}
},
username: DataTypes.STRING,
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: { msg: '密碼必須填寫' },
notEmpty: { msg: '密碼不能為空字符串' }
},
set(value) {
if (value.length >= 6 && value <= 45) {
this.setDataValue('password', bcryptjs.hashSync(value, 10))
} else {
throw new Error("密碼長度為6~45");
}
}
},
nickname: DataTypes.STRING,
sex: DataTypes.TINYINT,
company: DataTypes.STRING,
introduce: DataTypes.TEXT,
role: DataTypes.TINYINT,
avatar: DataTypes.STRING
}, {
sequelize,
modelName: 'User',
});
return User;
};