1// model.js
2import { Sequelize, Model, DataTypes } from 'sequelize'
3import { user, password, host, database } from './database.js'
4
5const sequelize = new Sequelize(database, user, password, {
6 host,
7 dialect: 'postgres',
8 logging: false
9})
10
11export class User extends Model {}
12
13User.init(
14 {
15 email: {
16 type: DataTypes.STRING,
17 allowNull: false
18 },
19 password: {
20 type: DataTypes.STRING,
21 allowNull: false
22 }
23 },
24 {
25 sequelize,
26 modelName: 'user',
27 timestamps: false,
28 hooks: {
29 beforeCreate: async user => {
30 const saltRounds = 10
31 const salt = await bcrypt.genSalt(saltRounds)
32 user.password = await bcrypt.hash(user.password, salt)
33 }
34 }
35 }
36)
37
38User.prototype.isPasswordValid = async function(password) {
39 return await bcrypt.compare(password, this.password)
40}
41
42// usage
43const { email, password, passwordconfirmation } = req.body
44const user = await User.create({ email, password })
45Created on 3/15/2021