示例#1
0
        public IActionResult DeleteUserPost(int userId, [FromQuery] int postId)
        {
            var cmd    = new DeleteUserPostCommand(userId, postId);
            var result = commandProcessor.Process(cmd);

            if (!result.Success)
            {
                return(BadRequest());
            }

            return(Ok(result.Response));
        }
示例#2
0
        public CommandResult <long?> Handle(DeleteUserPostCommand command)
        {
            var result = new CommandResult <long?>();

            try
            {
                var userId = command.UserId;
                var postId = command.PostId;

                var dbUser = ctx.Users.SingleOrDefault(u => u.Id == userId);
                var dbPost = ctx.Posts.SingleOrDefault(p => p.Id == postId);

                if (dbUser == null)
                {
                    logger.LogWarning($"Unable to find [{nameof(User)}] with Id: [{userId}]");
                    result.Success = false;
                    return(result);
                }

                if (dbPost == null)
                {
                    logger.LogWarning($"Unable to find [{nameof(Post)}] with Id: [{postId}]");
                    result.Success = false;
                    return(result);
                }

                if (dbPost.AuthorId != userId)
                {
                    logger.LogWarning($"Post [{postId}] does not belong to [{nameof(User)}] [{userId}]. Refusing the delete request.");
                    result.Success = false;
                    return(result);
                }

                ctx.Posts.Remove(dbPost);
                ctx.SaveChanges();

                result.Success  = true;
                result.Response = postId;
            }
            catch (Exception e)
            {
                logger.LogError(e.Message);
            }

            return(result);
        }