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.
Implement the method in UserService.cs
:
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
:
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
recipientId
exists - if it doesn't, returnNotFound()
Create a new
Follow
entityAdd the new
Follow
entity - 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