Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] Implement Endpoint for Updating a Comment on a Blog #432

Open
wants to merge 12 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
using System.Linq.Expressions;
using AutoMapper;
using Hng.Application.Features.Comments.Commands;
using Hng.Application.Features.Comments.Dtos;
using Hng.Application.Features.Comments.Handlers;
using Hng.Domain.Entities;
using Hng.Infrastructure.Repository.Interface;
using Hng.Infrastructure.Services.Interfaces;
using Moq;
using Xunit;

public class UpdateCommentCommandShould
{
private readonly IMapper _mapper;
private readonly Mock<IRepository<Comment>> _commentRepositoryMock;
private readonly Mock<IAuthenticationService> _authenticationServiceMock;
private readonly UpdateCommentCommandHandler _handler;

public UpdateCommentCommandShould()
{
// Setup AutoMapper
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<UpdateCommentDto, Comment>().ReverseMap();
cfg.CreateMap<Comment, CommentDto>().ReverseMap();
});
_mapper = configuration.CreateMapper();

_commentRepositoryMock = new Mock<IRepository<Comment>>();
_authenticationServiceMock = new Mock<IAuthenticationService>();
_handler = new UpdateCommentCommandHandler(
_mapper,
_commentRepositoryMock.Object,
_authenticationServiceMock.Object
);
}

[Fact]
public async Task Handle_ShouldUpdateCommentSuccessfully()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = "Updated content" };
var comment = new Comment
{
Id = commentId,
BlogId = blogId,
AuthorId = userId,
Content = "Original content",
CreatedAt = DateTime.UtcNow
};

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync(comment);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(userId);

_commentRepositoryMock
.Setup(r => r.UpdateAsync(It.IsAny<Comment>()))
.Returns(Task.CompletedTask);

_commentRepositoryMock
.Setup(r => r.SaveChanges())
.Returns(Task.CompletedTask);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, userId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(200, result.StatusCode);
Assert.Equal("Comment updated successfully", result.Message);
Assert.Equal("Updated content", result.Data.Content);
_commentRepositoryMock.Verify(r => r.UpdateAsync(It.IsAny<Comment>()), Times.Once);
_commentRepositoryMock.Verify(r => r.SaveChanges(), Times.Once);
}

[Fact]
public async Task Handle_ShouldReturnNotFound_WhenCommentNotFound()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = "Updated content" };

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync((Comment)null);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(userId);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, userId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(404, result.StatusCode);
Assert.Equal("Comment not found.", result.Message);
Assert.Null(result.Data);
}

[Fact]
public async Task Handle_ShouldReturnUnauthorized_WhenUserIsNotAuthorized()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var anotherUserId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = "Updated content" };
var comment = new Comment
{
Id = commentId,
BlogId = blogId,
AuthorId = userId,
Content = "Original content",
CreatedAt = DateTime.UtcNow
};

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync(comment);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(anotherUserId);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, anotherUserId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(403, result.StatusCode);
Assert.Equal("You are not authorized to update this comment.", result.Message);
Assert.Null(result.Data);
}

[Fact]
public async Task Handle_ShouldReturnBadRequest_WhenContentIsEmpty()
{
// Arrange
var blogId = Guid.NewGuid();
var commentId = Guid.NewGuid();
var userId = Guid.NewGuid();
var updateCommentDto = new UpdateCommentDto { Content = string.Empty };
var comment = new Comment
{
Id = commentId,
BlogId = blogId,
AuthorId = userId,
Content = "Original content",
CreatedAt = DateTime.UtcNow
};

_commentRepositoryMock
.Setup(r => r.GetBySpec(It.IsAny<Expression<Func<Comment, bool>>>()))
.ReturnsAsync(comment);

_authenticationServiceMock
.Setup(s => s.GetCurrentUserAsync())
.ReturnsAsync(userId);

// Act
var result = await _handler.Handle(
new UpdateCommentCommand(blogId, commentId, updateCommentDto, userId),
CancellationToken.None
);

// Assert
Assert.NotNull(result);
Assert.Equal(400, result.StatusCode);
Assert.Equal("Comment cannot be empty.", result.Message);
Assert.Null(result.Data);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Hng.Application.Features.Comments.Dtos;
using Hng.Application.Shared.Dtos;
using MediatR;

namespace Hng.Application.Features.Comments.Commands
{
public class UpdateCommentCommand(Guid blogId, Guid commentId, UpdateCommentDto body, Guid userId) : IRequest<SuccessResponseDto<CommentDto>>
{
public Guid BlogId { get; } = blogId;
public Guid commentId { get; } = commentId;
public UpdateCommentDto CommentBody { get; } = body;
public Guid userId { get; } = userId;
}
}
10 changes: 10 additions & 0 deletions src/Hng.Application/Features/Comments/Dtos/UpdateCommentDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace Hng.Application.Features.Comments.Dtos;

public class UpdateCommentDto
{
[JsonPropertyName("content")]
public string Content { get; set; } = string.Empty;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using AutoMapper;
using Hng.Application.Features.Comments.Commands;
using Hng.Application.Features.Comments.Dtos;
using Hng.Application.Shared.Dtos;
using Hng.Domain.Entities;
using Hng.Infrastructure.Repository.Interface;
using Hng.Infrastructure.Services.Interfaces;
using MediatR;

namespace Hng.Application.Features.Comments.Handlers;

public class UpdateCommentCommandHandler(
IMapper mapper,
IRepository<Comment> commentRepository,
IAuthenticationService authenticationService)
: IRequestHandler<UpdateCommentCommand, SuccessResponseDto<CommentDto>>
{
private readonly IMapper _mapper = mapper;
private readonly IRepository<Comment> _commentRepository = commentRepository;
private readonly IAuthenticationService _authenticationService = authenticationService;

public async Task<SuccessResponseDto<CommentDto>> Handle(UpdateCommentCommand request, CancellationToken cancellationToken)
{
var comment = await _commentRepository.GetBySpec(c => c.Id == request.commentId && c.BlogId == request.BlogId);
if (comment == null)
{
return new SuccessResponseDto<CommentDto>
{
Data = null,
Message = "Comment not found.",
StatusCode = 404
};
}

var userId = await _authenticationService.GetCurrentUserAsync();
if (comment.AuthorId != userId)
{
return new SuccessResponseDto<CommentDto>
{
Data = null,
Message = "You are not authorized to update this comment.",
StatusCode = 403
};
}

if (string.IsNullOrWhiteSpace(request.CommentBody.Content))
{
return new SuccessResponseDto<CommentDto>
{
Data = null,
Message = "Comment cannot be empty.",
StatusCode = 400
};
}

// Update only the content field
comment.Content = request.CommentBody.Content;
comment.UpdatedAt = DateTime.UtcNow;

await _commentRepository.UpdateAsync(comment);
await _commentRepository.SaveChanges();

return new SuccessResponseDto<CommentDto>
{
Data = _mapper.Map<CommentDto>(comment),
Message = "Comment updated successfully",
StatusCode = 200
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class CommentMapperProfile : Profile
public CommentMapperProfile()
{
CreateMap<CreateCommentDto, Comment>();
CreateMap<UpdateCommentDto, Comment>();
CreateMap<Comment, CommentDto>()
.ReverseMap();
}
Expand Down
1 change: 1 addition & 0 deletions src/Hng.Domain/Entities/Comment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ public class Comment : EntityBase
public User Author { get; set; }

public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
}
Loading
Loading