9.2: Retrieve Followees in API

Next, we'll add functionality to retrieve a list of Users another User has followed. We'll do this with query parameters, although you could do it using a separate endpoint.

Update UserParams

In the UserParams.cs file, add two properties: one for Followers and one for Followees. Both will have a default value of 'false'.

public bool Followees { get; set; } = false;
public bool Followers { get; set; } = false;

Update UserService

In UserService.cs - first we'll add a private method to retrieve either the followers or followees of a user.

private async Task<IEnumerable<Follow>> GetUserFollows(int id, bool followers)
{
    var user = await _context.Users
                .Include(x => x.Followee)
                .Include(x => x.Follower)
                .FirstOrDefaultAsync(u => u.Id == id);

    if (followers)
    {
        return user.Followee.Where(u => u.FolloweeId == id);
    }
    else
    {
        return user.Follower.Where(u => u.FollowerId == id);
    }
}

If there is a parameter for 'followers', we'll return all of the users that are being followed by the user with the passed in id.

If not, we'll return the users that are following the user.

Next, in the GetUsers() method we have already written - we'll add checks for query parameters for followers or followees being passed in:

if (userParams.Followers)
{
    var userFollowers = await GetUserFollows(userParams.UserId, userParams.Followers);
    users = users.Where(u => userFollowers.Any(follower => follower.FollowerId == u.Id));
}

if (userParams.Followees)
{
    var userFollowees = await GetUserFollows(userParams.UserId, userParams.Followers);
    users = users.Where(u => userFollowees.Any(followee => followee.FolloweeId == u.Id));
}

Testing in Postman

Now, if we send a GET request to /api/users?followees=true we should get back the user we previously followed while testing:

Last updated