{"size": 1516, "ext": "js", "max_stars_repo_path": "server/services/user.services/followUser.js", "max_stars_repo_name": "savyasachi16/Twitter-prototype", "max_stars_repo_stars_event_min_datetime": "2021-04-27T20:28:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T20:28:34.000Z", "max_issues_repo_path": "server/services/user.services/followUser.js", "max_issues_repo_name": "tinaaggarwal/Twitter-prototype", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/services/user.services/followUser.js", "max_forks_repo_name": "tinaaggarwal/Twitter-prototype", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.4516129032, "max_line_length": 83, "alphanum_fraction": 0.4604221636}
/* eslint-disable no-underscore-dangle */
import Users from '../../models/user.model';

const handleRequest = (payload, callback) => {
  const { userId, followerId } = payload;
  // Find the current user
  Users.findById(userId).then(user => {
    if (!user) {
      callback(
        {
          message: 'User not found!',
        },
        null
      );
    } else {
      // Find the user whom the current user wishes to follow
      Users.findById(followerId).then(followingUser => {
        if (!followingUser) {
          callback(
            {
              message: 'User not found!',
            },
            null
          );
        } else {
          user.following.push(followingUser._id);
          followingUser.followers.push(user._id);
          const userUpdatePromise = Users.findOneAndUpdate(
            {
              _id: user._id,
            },
            {
              $addToSet: {
                following: followingUser._id,
              },
            }
          );
          const followingUserUpdatePromise = Users.findOneAndUpdate(
            {
              _id: followingUser._id,
            },
            {
              $addToSet: {
                followers: user._id,
              },
            }
          );
          Promise.all([userUpdatePromise, followingUserUpdatePromise]).then(() => {
            callback(null, {
              message: 'Followed',
            });
          });
        }
      });
    }
  });
};

export default {
  handleRequest,
};
