Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Entities;
- using Entities.Exceptions;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Service.Contracts;
- using Shared.DataTransferObjects;
- using System.ComponentModel.Design;
- using System.Diagnostics;
- [ApiController]
- [Route("api/likes")]
- public class LikeController : ControllerBase
- {
- private readonly IServiceManager _service;
- public LikeController(IServiceManager service)
- {
- _service = service;
- }
- [HttpGet("post/{postId}")]
- [Authorize]
- public async Task<IActionResult> GetLikesForPost(Guid postId)
- {
- var likes = await _service.LikeService.GetLikesAsync(postId, "post", trackChanges: false);
- return Ok(likes);
- }
- [HttpGet("comment/{commentId}")]
- [Authorize]
- public async Task<IActionResult> GetLikesForComment(Guid commentId)
- {
- var likes = await _service.LikeService.GetLikesAsync(commentId, "comment", trackChanges: false);
- return Ok(likes);
- }
- [HttpPost]
- [Authorize]
- public async Task<LikeDto> CreateLike([FromBody] LikeForCreationDto likeDto)
- {
- var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == "UserId").Value;
- var displayName = _service.UserService.GetUserName(User);
- LikeDto like;
- if (likeDto.CommentId != null && likeDto.CommentId is Guid)
- {
- likeDto.PostId = null;
- Guid commentId = (Guid)likeDto.CommentId;
- like = await _service.LikeService.CreateLikeAsync(userIdClaim, displayName, likeDto);
- await _service.CommentService.UpdateLikeCount(commentId, increment: true, trackChanges: true);
- return like;
- }
- if (likeDto.PostId != null)
- {
- likeDto.CommentId = null;
- Guid postId = (Guid)likeDto.PostId;
- like = await _service.LikeService.CreateLikeAsync(userIdClaim, displayName, likeDto);
- await _service.PostService.UpdateLikeCount(postId, increment: true, trackChanges: true);
- return like;
- }
- else
- {
- return null;
- }
- }
- [HttpDelete("{likeId}")]
- public async Task<IActionResult> DeleteLike(Guid likeId)
- {
- try
- {
- await _service.LikeService.DeleteLikeAndUpdatePostAsync(likeId);
- return NoContent(); // Returns a 204 No Content response on successful deletion
- }
- catch (LikeNotFoundException ex)
- {
- return NotFound(ex.Message); // Returns a 404 Not Found if the like does not exist
- }
- catch (Exception ex)
- {
- // Log the exception details
- return StatusCode(500, "An error occurred while processing your request."); // Returns a 500 Internal Server Error for any other exceptions
- }
- }
- }
Add Comment
Please, Sign In to add comment