Nodejs mysql is assigning empty value

Viewed 20

I am using nodejs and mysql and I have controller, route, and auth middleware for authenticating the user.

Route

router.route("/profile").get(protect, getUserProfile);

protect middle ware

const protect = asyncHandler(async (req, res, next) => {
  let token;
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      token = req.headers.authorization.split(" ")[1];
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      console.log("Decoded value");
      console.log(decoded);
      let sql =
        "select @uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT @uid := NULL) init_var where email=?;select @finaluid:= `user_id` from user_type, (SELECT @finaluid := NULL) init_var  where user_id =@uid AND type='customer';select customer_id from customer where user_id =@finaluid;";
      db.query(sql, [decoded.id], (err, result) => {
        if (result) {
          req.user = result;
        } else {
          res.status(404);
          res.json(err);
        }
      });

      next();
    } catch (error) {
      console.error(error);
      res.status(401);
      throw new Error("Not authorized, token failed");
    }
  }
  if (!token) {
    res.status(401);
    throw new Error("Not authorized, no token");
  }
  next();
});

Here I am passing the value of `result` to the `req.user` but it gets assigned empty value. When I try to access `req.user` value from controller like this,
But result do have a value.

controller

const getUserProfile = asyncHandler(async (req, res) => {
  console.log("controller req.user value");
  console.log(req.user);
  res.json(req.user);
});

But here res.json gives nothing and log give undefined.
Is it async and await that I am missing? How do I solve this?
1 Answers

db.query has a callback waiting, but you run next in parallel, so you are moving to the next middleware before waiting for the callback to be executed.

db.query(sql, /**/);
next();

You should:

db.query(sql, [decoded.id], (err, result) => {
    if (result) {
      req.user = result;
     
     next(); // call here the next middleware

    } else {
      res.status(404);
      res.json(err);
    }
  });

But you will need to make sure all the branches are covered in your code.

Related