9.1: Follow a User in API
Update UserService
We'll just add one method to for this, so we'll add it to the UserService. Alternatively, you could create a new FollowService if you forsee the application expanding after you finish the tutorial. For now, we'll keep them together for simplicity's sake.
In IUserService.cs, add a new method signature called GetFollow. Again, the wording here is a bit awkward - but, think of this as a 'follow event' - a case of one user following another.
Task<Follow> GetFollow(int userId, int recipientId);Implement the method in UserService.cs:
public async Task<Follow> GetFollow(int userId, int recipientId)
{
return await _context
.Follows
.FirstOrDefaultAsync(u => u.FollowerId == userId &&
u.FolloweeId == recipientId);
}We'll use this method to check if a User has already followed a particular User.
Update UsersController
Next, we'll add a new POST method to UsersController.cs:
[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.
}Check whether the token has rights to access this endpoint.
Gets the 'follow event` from the database
Checks if it isn't null - if it is, it returns a
BadRequest()Checks whether the user with the given
recipientIdexists - if it doesn't, returnNotFound()Create a new
FollowentityAdd the new
Followentity - using the genericAdd()method we created earlierTries to save changes to the database. If successful, it returns
Ok()If unsuccessful, it returns a
BadRequest()
Test in Postman
Get a fresh token from the user you'd like to use. Also, either from the database, or sending a GET request to /api/users, pick out a different user you'd like to 'follow.'
In Postman, send a POST request to localhost:5000/api/users/{userId}/follow/{followId}. (Where userId is the id of the user you have a token for, and followId is the id of the user you want to follow).
You should get a 200 OK response:

You can check the database, to make sure the 'follow event' was added correctly:

If you attempt to 'refollow' the same User (by resending your previous request), you should get a 400 Bad Request response with You already followed this user in the body:

Last updated