Socket.io bug after success request

Guys!
Expected some bug with my socket.io.
So, all work fine. Below you can see the code example:

Server (Node.js):

controller:

.put('/user', jwtMiddleware, (req, res, next) => userService.updateUser(req.user.id, req.body.imageId, req.body)
    .then(data => res.send(data))
    .catch(err => {
      console.log(err.message); <------ LOOK AT THIS (1)
      req.io.to(req.user.id).emit('user_data', err.message); // notify a user if username or email isn't unique
      res.status(400).send();
      next();
    }));

P.S. io injected to the request object.

userService.updateUser.js:

export const updateUser = async (userId, imageId, user) => {
  const userByName = await userRepository.getByUsername(user.username);

  if (userByName !== null && userByName.id !== userId) {
    throw new Error('Username should be unique');
  }

  const { id } = await userRepository.updateById(userId, {
    ...user,
    imageId
  });
  return getUserById(id);
};

Below you can see client code (React.js):

socket.on('user_data', message => {
   console.log(message); <----- LOOK AT THIS (2)
   NotificationManager.info(message);
});

And now time for explaining the problem.

a) When I send my user object from client to controller with ‘username’ that has already existed in the DB, I wonderful receive response on the client and my socket on the client in the places (1) (2) well work.

b) But when I send my user object from the client to the controller with ‘username’ that doesn’t exist in the DB, it will fine save in the DB and after that, if I send a request as in point (a), I won’t receive a response on the client. My socket on the server in a place (1) WORK CORRECTLY and in a place (2) ISN’T WORK.

Why has it happened?

78 thoughts on “Socket.io bug after success request”

Leave a Comment