Exemplo n.º 1
0
        public async Task <IActionResult> AddComment([FromForm] int postId, [FromForm] string content)
        {
            var post = await _postService.GetPostWithUserAsync(postId);

            if (post == null)
            {
                return(NotFound());
            }

            var currentUserId = await _userService.GetCurrentUserIdAsync();

            var comment = new Comment
            {
                Content     = content,
                CommentById = currentUserId,
                PostId      = post.Id,
            };

            await _postService.AddCommentToPostAsync(comment);

            await _unitOfWork.CompleteAsync();

            var userSetting = await _userService.GetUserSettingUserIdAsync(post.CreatedBy.Id);

            //Notify the user who created the post
            if (!post.IsForCurrentUser(currentUserId))
            {
                if (userSetting.NotifyWhenUserCommentOnPost)
                {
                    var attributes = new List <NotificationAttribute>
                    {
                        new NotificationAttribute
                        {
                            Name  = "CommentId",
                            Value = comment.Id.ToString()
                        },
                        new NotificationAttribute
                        {
                            Name  = "PostId",
                            Value = post.Id.ToString()
                        }
                    };
                    var notification =
                        new Notification(post.CreatedBy, currentUserId, NotificationType.Comment, attributes);

                    post.CreatedBy.CreateNotification(notification);

                    await _unitOfWork.CompleteAsync();

                    await _notificationService.PushNotification(post.CreatedBy.Id, notification.Id);
                }
            }

            await _unitOfWork.CompleteAsync();


            var model = new CommentViewModel
            {
                Comments = new List <Comment>
                {
                    comment
                },
            };

            var commentTemplate = await _renderService.RenderViewToStringAsync("Templates/_Comment", model);

            return(Json(new
            {
                postId = comment.PostId,
                totalComments = await _postService.GetTotalCommentsForPostAsnyc(comment.PostId),
                comment = commentTemplate
            }));
        }