Home > database >  Call a new function after result of user creation in Sequelize
Call a new function after result of user creation in Sequelize

Time:03-02

I have this code :

const saltRounds = 10;

let charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

module.exports.addUser = async (req, res) => {
  try {
    let userData = req.body;
    let email = userData.email;


    for (i = 0; i <= 15; i  ) {
      let randomNumber = Math.floor(Math.random() * charset.length);
      password  = charset.substring(randomNumber, randomNumber   1);
    }

    bcrypt.hash(password, saltRounds, function (err, hash) {
      password = hash;

      userData.password = password;

    });

} catch (err) {
    console.log(err);
    res.status(500).json("Server error");
  }
};
 

I get datas from the front end, and then I generate a random password which I add to the userData variable.

What I want now, is to call that function to create a user in database :

const newUser = await User.createUser(userData, res);

And be able to request the user I have just created from the database to make other stuff just after creation with that :

const user = await User.getUser(email);

I have tried different things, but every time I have a problem with the order of execution. For instance, the program tries to get user infos before it is created etc ...

CodePudding user response:

I don't know why are you fetching the details again if they're already available when you create user.

const newUser = await User.createUser(userData, res);
// newUser has all the values you're trying to fetch

bcrypt hash retruns promise if call is not specified

module.exports.addUser = async (req, res) => {
  try {
    let userData = req.body;
    let email = userData.email;


    for (i = 0; i <= 15; i  ) {
      let randomNumber = Math.floor(Math.random() * charset.length);
      password  = charset.substring(randomNumber, randomNumber   1);
    }

     const hash = await bcrypt.hash(password, saltRounds)
      if(hash) {
      password = hash;
      userData.password = password;
     }
      //then the create user promise code

} catch (err) {
    console.log(err);
    res.status(500).json("Server error");
  }
};
 

That's not how promise works. to work with the promise sequentially you can do something like this

let newUserData = null
Promise.all([ User.createUser(userData, res), User.getUser(email);])
        .then((result) =>  newUserData = result[0]);
         // the result will be an array the 1st element will be the response of User.createUser(userData, res) and respective other 

let me know if this helps!

  • Related