9.1: Follow a User in API
Update UserService
Task<Follow> GetFollow(int userId, int recipientId);public async Task<Follow> GetFollow(int userId, int recipientId)
{
return await _context
.Follows
.FirstOrDefaultAsync(u => u.FollowerId == userId &&
u.FolloweeId == recipientId);
}Update UsersController
[HttpPost("{id}/follow/{recipientId}")]
public async Task<IActionResult> FollowUser(int id, int recipientId)
{
if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) // 1.
return Unauthorized();
var follow = await _userService.GetFollow(id, recipientId); // 2.
if (follow != null) // 3.
return BadRequest("You already followed this user.");
if (await _userService.GetUser(recipientId) == null) // 4.
return NotFound();
follow = new Follow // 5.
{
FollowerId = id,
FolloweeId = recipientId
};
_userService.Add<Follow>(follow); // 6.
if (await _userService.SaveAll()) // 7.
return Ok();
return BadRequest("Failed to add user."); // 8.
}Test in Postman



Last updated