Creating Basket Controller
In this lesson, we're going to create basket controller
Creating Basket controller#
We have created our Basket and BasketItem entity, and we have created the migration as well. Let's create our BasketController now. Inside our API project and controllers, let's create our BasketController — we will derive it from our BaseController. We can create an empty constructor and inject our Store context for now. We'd import it and initialize it from parameter. You must be wondering why we haven't used our generic repository for this. Well, you definitely can, but the main advantage of using it is when there are multiple use cases and you have to repeat the code again and again.
Let's see how it goes and if there's a need to create a generic repository for the methods, we'll do that as well. For now, let's proceed with the storeContext, and create our three methods. Let's start with the getBasket method. We'd write HttpGet since it's going to be a get method. Below this, let's write our method, public async Task of ActionResult, and we will return a Basket, which we'll call GetBasket. Let's import Task from System.Threading.Tasks, Action result from Microsoft.AspNetCore.Mvc and basket using Entity. Inside the method, let's create a new variable, basket, then we'll use our context, .Baskets. Now we need a unique identifier to identify the user's particular basket. How can we do it? When we create a new basket, we can create an id which we can send as a response that will be saved in the user's browser as cookies. Then with every request, client will send this client Id, and this is how we will know which basket the customer is interacting with. Now we can write FirstOrDefaultAsync and check if x.ClientId, which is stored in our database, is equal to the client's cookie which we can check as Request.Cookies.
Now, doing this will give us the basketId and clientId, but if you remember, it also has navigation properties. We have Items and Items has Course. Inside our generic repository, we made a specification for doing this, but since we are not using genericRepository here, we can chain this with include statement. We will include the Items first, and after this, we want to use another navigation property, so we will use ThenInclude, which will be i.Course. Now if the basket is null, we will return NotFound response with new ApiRespose with status code 404. If it's not null, we will return the basket.