Home > database >  Unexpected error while trying to store user with sequelize
Unexpected error while trying to store user with sequelize

Time:12-28

I'm relative new to node.js and sequelize and promises in js. But I don't understand why my program is giving me back my error message even when the user is created successfully.

My sequelize model, reading the docs and some answers here I added the hook to encrypt the password:

const Sequelize = require('sequelize');
const bcrypt = require('bcrypt');

const db = require('../util/config');

const User = db.define('user', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  userName: {
    type: Sequelize.STRING(250),
    allowNull: false
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  type: {
    type: Sequelize.INTEGER,
    allowNull: false
  }
},
  {
    hooks: {
      beforeCreate: async (user) => {
        const hashedPassword = await bcrypt.hash(user.password, 8);
        user.password = hashedPassword;
      }
    }
  }
);
module.exports = User;

And this is the middleware that I use for storing the user

const User = require('../models/user');
const Patient = require('../models/patient');
const bcrypt = require('bcrypt');

exports.newUser = (req, res, next) => {
  const errors = validationResult(req);
  console.log('REQUEST', req.body);
  if (errors.isEmpty()) {
    checkPerson(req.body).then((existPerson) => {
      if (existPerson) {
        checkUser(req.body).then((existUser) => {
          if (!existUser) {
            User.create(req.body)
              .then((res) => {
                res.status(201).json({ // 201 = OK, pero creado un recurso
                  message: 'Saved successfully',
                  data: {
                    generatedId: res.dataValues.id,
                    patientCreated: res.dataValues
                  }
                })
              })
              .catch((error) => {
                res.status(400).json({
                  message: 'Error while creating user',
                  DBError: error
                })
              });
          } else {
            res.status(200).json({
              message: 'The person already has an user, please login'
            })
          }
        })
      } else {
        res.status(200).json({
          message: 'No person found with that id',
        })
      }
    })
  } else {
    res.status(502).json({
      message: 'Data validation error',
      validationErrors: errors.array()
    })
  }
}

function checkPerson(payload) {
  // console.log('checkPerson payload', payload)
  const userType =  payload.type;
  switch (userType) {
    case 1: // PATIENT
      return new Promise(resolve => {
        resolve(
          Patient.findOne({
            where: {
              id: payload.patientId
            }
          }).then(user => { return user ? true : false })
        )
      })
  }
}

function checkUser(payload) {
  return new Promise(resolve => {
    resolve(
      User.findOne({
        where: {
          patientId: payload.patientId,
        }
      }).then((user) => {
        return user ? true : false;
      })
    )
  })

}

My middleware checks if the Patient (in this case) exists, then checks if the patient has an user, and if not it creates it. But the response that I get is 'Error while creating user', but if I check the database the user has been created successfully and I don't know why, Any help is appreciated. Thanks in advance

CodePudding user response:

Looks like the problem lies within the then clause. Instead of using res for both the User.create response and HTTP response, you should probably change it to something else, for example:

.then((createResponse) => {
    res.status(201).json({ // 201 = OK, pero creado un recurso
        message: 'Saved successfully',
        data: {
            generatedId: createResponse.dataValues.id,
            patientCreated: createResponse.dataValues
        }
    })
})
  • Related