This video is available to students only

Changing Basket Logic

In this lesson, we're going to change the basket logic

Changing basket logic#

Now that we are able to sign in as a user, we need to make some changes to the basket logic. Let me explain. When the user is not signed in, they can still add items to the basket. But when they sign in as a user, what happens to that basket? Sounds a little complicated, but it's not. When a user adds items to the basket and then signs in, we simply want to transfer that basket to the user using the clientId cookie. If they don't add anything to the basket, we can simply return the old basket which was created with their username.

Let's see that in action. We can go to the Basket Controller and inside the Extract basket function, we were previously extracting the cookie from the request and fetching the basket, but now we will take client id as a parameter so let's write that. Now we will check if the client Id is empty using string.IsNullOrEmpty. In this case, we will delete the cookie just to make sure, and will return null; which means if there's no clientId, there's no basket. If there is a clientId, we will use the same logic. We will simply replace this cookie with clientId.

Now all our functions are complaining because they are not passing the client id. Let's create a private function for that which can be called GetClientId; this function will check if the user exists. It will return the Name of the user; otherwise, it will check the Request cookie with name, client id. So, we can write User.Identity?.Name, and we can use a question mark because the field Identity might not exist. If it's null, we will use Request.Cookies. We can now use this function everywhere we are making the ExtractBasket method call.

Also, we need to change the logic for CreateBasket method. We will first try to assign the clientId to the user name, so we can check if User.Identity?.Name; this means the user is logged in. If this is empty, we will use the old assignment of using Guid.NewGuid().ToString(). This simply means that the user is not logged in.

Start a new discussion. All notification go to the author.