Outline

Demo: Implement Follow & Unfollow in Repository

In the Conduit.Repositories Project

Modify ProfileRepository:
  • Hover over the error on IProfileRepository
  • select [Show Potential Fixes]
  • Select [Generate method]
Add the following to the body of the method to FollowAsync:
public async Task<UserProfile> Follow(string userName)
{
        Person person = await GetPersonAndFollowersAsync(userName);
        if (person is null)
                throw new ProfileNotFoundException($"Profile for [{userName}] is not found.");

        Account loggedInUser = await AccountRepo.GetLoggedInUserAsync();
        UserProfile profile = await CreateProfileAsync(person);
        if (!profile.Following)
        {
                Follow follow = new Follow { Follower = loggedInUser.Id, Following = person.Id };
                Context.Follows.Add(follow);
                await Context.SaveChangesAsync();
                profile.Following = true;
        }
        return profile;
}
Add the following to the body of the method to UnfollowAsync:

public async Task Unfollow(string userName)

{
        Person person = await GetPersonAndFollowersAsync(userName);
        if (person is null)
                throw new ProfileNotFoundException($"Profile for [{userName}] is not found.");

        Account loggedInUser = await AccountRepo.GetLoggedInUserAsync();
        UserProfile profile = await CreateProfileAsync(person);
        if (profile.Following)
        {
                Follow follow = await Context.Follows.FindAsync(loggedInUser.Id, person.Id);
                Context.Follows.Remove(follow);
                await Context.SaveChangesAsync();
                profile.Following = false;
        }
        return profile;
}

Remember to type out the code and understand the logic. You're not learning anything if you're copying & pasting (unless indicated in the video).

 

I finished! On to the next chapter