Skip to content

Commit

Permalink
Created delete friend API endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
wesleypayton committed May 23, 2024
1 parent 10e57f6 commit 1edd2a1
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/FocusAPI/Controllers/SocialController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ public async Task<ActionResult<List<FriendListModel>>> GetAllFriends([FromQuery]
return Ok(result);
}

[HttpDelete]
[Route("Friend")]
public async Task<ActionResult> DeleteFriend([FromBody] DeleteFriendCommand command)
{
try
{
await _mediator.Send(command);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error deleting friend");
return StatusCode((int)HttpStatusCode.InternalServerError);
}

return Ok();
}

[HttpGet]
[Route("AllFriendRequests")]
Expand Down
50 changes: 50 additions & 0 deletions src/FocusAPI/Methods/Social/DeleteFriend.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using FocusAPI.Data;
using FocusAPI.Models;
using FocusCore.Commands.Social;
using FocusCore.Commands.User;
using FocusCore.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace FocusApi.Methods.Social;
public class DeleteFriend
{
public class Handler : IRequestHandler<DeleteFriendCommand, Unit>
{
FocusAPIContext _context;
ILogger<Handler> _logger;
public Handler(FocusAPIContext context, ILogger<Handler> logger)
{
_context = context;
_logger = logger;
}

public async Task<Unit> Handle(DeleteFriendCommand command, CancellationToken cancellationToken)
{
try
{
// Fetch friendship
var friendship = await _context.Friends
.Include(f => f.User)
.Include(f => f.Friend)
.FirstOrDefaultAsync(f => f.UserId == command.UserId && f.FriendId == command.FriendId);

// Remove friend entry
friendship.User.Inviters?.Remove(friendship);

friendship.Friend.Invitees?.Remove(friendship);

_context.Friends.Remove(friendship);

await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error removing friendship from database");
}

return Unit.Value;
}
}
}
13 changes: 13 additions & 0 deletions src/FocusCore/Commands/Social/DeleteFriendCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FocusCore.Commands.Social;
public class DeleteFriendCommand : IRequest<Unit>
{
public Guid UserId { get; set; }
public Guid FriendId { get; set; }
}

0 comments on commit 1edd2a1

Please sign in to comment.