Esempio n. 1
0
        public async Task <IActionResult> Post(
            int id,
            [FromQuery(Name = "token")] string token)
        {
            ModelResult <UserFollowInfo> result = TokenUtils.CheckToken <UserFollowInfo>(token, _context);

            if (result != null)
            {
                return(BadRequest(result));
            }

            Session sessionResult = await _context.Sessions
                                    .FirstOrDefaultAsync(s => s.SessionToken == token);

            User follower = await _context.Users
                            .FirstOrDefaultAsync(u => u.UserId == sessionResult.SessionUserId);

            UserFollow userFollowResult = await _context.UserFollows
                                          .FirstOrDefaultAsync(uf => uf.FollowingId == id &&
                                                               uf.FollowerId == sessionResult.SessionUserId);

            if (userFollowResult != null)
            {
                result = new ModelResult <UserFollowInfo>(400, null, "User Followed");
                return(BadRequest(result));
            }

            User following = await _context.Users
                             .FirstOrDefaultAsync(u => u.UserId == id);

            if (following == null)
            {
                result = new ModelResult <UserFollowInfo>(404, null, "User Not Exists");
                return(BadRequest(result));
            }

            UserFollow userFollow = new UserFollow
            {
                Follower    = follower,
                FollowerId  = follower.UserId,
                Following   = following,
                FollowingId = following.UserId
            };

            _context.Add(userFollow);
            await _context.SaveChangesAsync();

            await NoticeUtils.CreateFollowNotice(userFollow, _context);

            result = new ModelResult <UserFollowInfo>(201, null, "Add Follow Success");
            return(Ok(result));
        }