Node.js REST API with Express & MongoDB - Solid Architecture | RapidDev Pro | Skillshare

Node.js REST API with Express & MongoDB - Solid Architecture

RapidDev Pro, Full Stack Developer & Tech Entrepreneur

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
25 Lessons (3h 9m)
    • 1. Introduction

      4:22
    • 2. Install Nodejs and npm

      0:38
    • 3. Install MongoDB

      0:59
    • 4. Tools used in this course

      0:23
    • 5. Object and Array destructuring

      6:03
    • 6. Spread Operator

      9:04
    • 7. Promise Vs Async await

      13:33
    • 8. API Overview

      5:08
    • 9. Setting Up Node.js Server

      6:15
    • 10. Express Middlewares

      9:08
    • 11. MongoDB Connectivity

      4:52
    • 12. Product Model & Schema-Mongoose

      2:40
    • 13. POST API: Create Product

      21:57
    • 14. Mongoose toObject Transform

      5:51
    • 15. Create Product API Schema

      6:12
    • 16. API Schema Validation Middleware

      14:54
    • 17. GET API: List Product with Pagination

      14:32
    • 18. GET API: Product by Id

      8:32
    • 19. PUT API: Update Product

      7:03
    • 20. DELETE API: Remove Product by Id

      3:07
    • 21. POST API: User SIgnup

      12:46
    • 22. POST API: User Login and JsonWebToken ( JWT )

      10:13
    • 23. Token Validation Middleware and Protect Product Routes with JWT

      9:51
    • 24. Swagger API Documentation

      10:16
    • 25. Source code

      0:24

About This Class

Build MVC Rest API with Node.js, Express.js & MongoDB. Secure REST API with JWT, document API with Swagger, Mongoose ODM

Want to learn how to build REST API with Nodejs, ExpressJs and MongoDB ?? If yes, then this course is for you. In this course you will learn how to create MVC pattern REST API architecture in Nodejs, communication with MongoDB using Mongoose, Securing API with JWT ( jsonwebtoken) and documenting API using popular open source tool called swagger.

We are in the world of REST API architecture because of boom in the micro-services. Every company is moving toward REST API architecture from traditional monolithic server architecture.

What is REST API ?

A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. 

Why MVC Pattern in REST API ?

MVC pattern/architecture allows you to decouple your code into various modules such as controller, services, models and routes so that you can scale your code without any burden of code maintenance as all the nodes in the MVC architecture works in sync and as expected.

You will learning the following things in this course:

♦  REST API in Nodejs and ExpressJs.

♦  MVC Architecture in REST API Nodejs.

♦  Interaction with MongoDB in nodejs using mongoose.

♦  Create, update, delete and find query using mongoose.

♦  Create list pagination API using mongoose pagination query in Nodejs.

♦  Secure REST API with JSONWEBTOKEN ( JWT ).

♦  Use tools such as POSTMAN to test API.

♦  Write middleware in Nodejs .

♦  Joi object schema validation in Nodejs .

♦  Host swagger documentation of your REST API on your API server itself.

♦  Create Re-usable services in REST API.

♦  Enable Cross-Origin Resource Sharing (CORS) in Nodejs REST API.

♦  Mongoose schema and models.

♦  HTTP request basics: Request body, path params, query params and headers.

♦  CRUD API in Nodejs.

♦  Login/Authenticate API to generate token.

♦  REST API Design.

♦  Node and NPM.

♦  and more.

Transcripts

1. Introduction: Hello, everyone on. Welcome to my course on building their Stabia with Norges Express and Mongo db. My name is a report of pro on. I'm going to be your instructor in this course. So let's quickly have a look at their Este Pia that we're going to build in the scores. So, as you can see, this is the PR conjecture on that we're going to implement. So at the bottom, if you can see there, is this that I exclaimed. Okay, so you're wrestling can be anything. It can be a Web Rosell native and or device or the IRS device. OK, any sort of claim that can interact with the extractive protocol. So as soon as they exclaimed saying the request, it will be handled by the roads in our Norges server. Okay, Now, for on the roads, we will make various decisions. Okay, So let's say you want to sometimes want to validate some off the stuff before proceeding for the successive, validating the token, okay? Or maybe validating the request data, presenting the payload or even in the very programs. Okay, so there are a couple off checks that you want to perform before persuading the request for the so for that will be implementing middle bed. Okay, so middleware will perform all sort off checks. And if any sort of validation feels, then it will basically signed this other back to declaim. Okay? And if the allegation is success, then it will basically trans for the request to the controller. And here in the controller, we're going to prepare their data that is required by the service. Okay, Andi Controller will basically call this service and said this is where you basically write the business logic. Okay, so here, civilian track with the database to get the data on service will then transferred this data back to the controller and controller will finally send the response to decline. Okay, so this is the end during flu that we're going to implement. And if you're wondering, why do we need service instead of writing the business logic in controller itself? So let me just tell you that as of now, we haven't implemented anything. But just for the sake of answering this, I would like to tell you that the controller is nothing but and called back to out. Right? So this has access to the request response Object Very service are basically normal function. Okay, so once you write your business logic in a normal function but you can do is you can basically reuse this particular logic. Okay, but if you would have returning in the controller, you wouldn't be able to reuse it. OK, since those are not normal function, those are callback function which has access to the request response. Object. Okay, so if you rate our business lodging in a normal function, it can be reused, OK? And you will not violate the dry principle which is do not repeat yourself. OK, so it will help your Lord because ah, lot off service will call internally other service to get the data. And let me just explain you example how this reusable service is going to help us. So as you can see on the screen, consider this example where we have to a be a The 4th 1 is to get the user detail, and the 2nd 1 is to get the order detail right off a particular user. So in the user to daily prayer. What you do is you basically ask for the user ready in the part perimeter. And you simply go to the user details office and first do data from the database and give response back to the client. Okay? And in case of order detail, we basically want to fess the order detail as well. Is the user details? Right? So you first of all go to the order details, have his throughout controller. OK, on Dhere in the order Little service, you basically interact with their database and get the order detail. OK, but now you also want the user details along with the order detail. Right? So one way that you can do it is by simply again hitting the database and fighting the user detail again. Or what you can do is since you already have returned your business logic insert of the user Details service which is simply a function residing in a particular file. What you can do is from the order little service, you can simply call this function. Okay, This service is nothing but a function so you can simply call dysfunction. Pause the user ready on that particular user detail service will return you the user to tell itself. So what you have done is here you have just to use the existing business logic. You haven't wrote it again. Ok, so this way you are basically reusing the existing piece off court, which is a good practice. Okay, on. And then we're also going toe document Arabia using the struggle, eh? Pretty So. This course has everything you need to build the recipe with Norges Express and Mom would be so I'm so excited to share all my knowledge and the learnings with you, and I hope to see you in Michael's. 2. Install Nodejs and npm : Hello, everyone on in this video, we're going to see how can you install nor Jess and NPM on your machine. So don't install it. You can simply visit, nor J start org. Then go with your download section on You can our downward according to an operating system . So as you can see, I have already downloaded all you have to really single double click an install. And once you're done with the installation you can head over to their terminal on. You can simply say Lord hyphen V to check the North version on NPM high friendly, protect the NP emergent. And then pin comes bundled with the Norges so you don't help. One started explicitly. So they're checked for this video. Andi, thank you so much for watching it. 3. Install MongoDB: Hello, everyone. So download the Mongol to be on your system, you can simply search for longer TV download center. Okay. And simply click on this website. Okay, on. Then you can click on the surfboard. Okay, Onda, we basically want to install the mongo DB server. Right? So once you go to this, our and then you can simply choose the communities over. Okay? Not the enterprise one. So just like the communities over, And then you can select the operating system as per unit and simply click on download. So once you don't really will get an executable file like this on simply the my click on this on, simply install it, OK? No one soon started. Simply go to the terminal on down this command, which is mongo. Okay, so you will see the shell version and everything. Okay, on you will see these locks. So if you get this, that means it is successful installed. Okay. So that so you can basically install them already. Been your system. So I hope you're able to follow along. And thank you so much for watching this video 4. Tools used in this course: Hello, everyone. So in this will do I just quickly wanted to show you the tools that we will be using in our course. So for the quarterly that I'm using, the V s scored on for their criminal. I'm using this. Come under terminal for windows. Okay. And if you want to have the exact same set up as me, and then you can download the stools. So you guys, that's it. Just wanted to give you a brief information regarding the same on. Thank you so much for watching this for you. 5. Object and Array destructuring: Hello, everyone. So in this video, we're going to understand what is day structuring on How can we use their de structuring? So districting basically allows you to fetch the properties from the object on values from the into individual variable. So let me show you by example or they mean by that. So here I'll create a file called as they structuring, nor Jay's OK, now in this file, I'm going to First World declared a user object. Okay, on this user object is going toe Hold some of the property such as name as David then we have ages. For example 22 then we have city as so like city on Finally, we have country as USA A OK, so let's say we have the user object now. What we want to do is we want to fat to the name and the country into individual variable. Okay, so the way you would do without the districting is very declaring available over here. So you would say const name equals user Gortney. And you would say const country equals user dark country. Okay, No, let me the same play playing these two variables over here, so I didn't say name as name A with you. Okay. And the same for the country. Okay, so now let me open up a terminal Onda on this particular fight. So here, I'm going to say Nord the structuring George's. So, as you can see, we got the name is David and the country, as you say. Okay, now let's see. How can we do the same using their day structuring? So is that blue Before that the succeeding allows you to fight city properties from the object. Okay. And here, really, as of now, using the object will also consider the example of theory. But let's first have a look at the object. So first of all, I'm going to commend this out and the way you can destructor this object is basing Const. Then you have the space of medical lib assists. Then you have to specify the property names that you want to fight from this object. And remember that this property name should match the properties president in the object. So, for example, I want to face the name and the country. Okay, so this is how I would do it and I'll pass the user object Okay, So what it will do is it will basically source for the name property in the user object and the current country property in this user object. Okay. And it is going toe create the same to individual variable with those values. OK, so this is not creating object. Okay, this implicating to conserve variable. So let me simply say this. And since we're control logging this very well, be sure against get the same dessert. Okay, so here, I'm going to see north. This fucking gorgeous so as you can see again, regard this individual variable. OK, so a lot of people get confused, like whether it is an object or something, but no, it is just creating two variables. Okay, This is how our districting works with the objects. No, let's understand. How can we deal with the party as well? Okay, so here, first of all, I'm going to declare in Caldas Maya on Let's assume that it is holding lusitans one toe, three and four. Ok, now let's say you want to fetch the force revalue into individual variable. Okay? So we don't restructuring. The way you can do it is blessing const. Food equals toe my array off zero. Then you would say, Const bar it will do my day off one and finally const. As equal do my a day off. Okay, so let me just spring this individual variable so that you can see properly for its food, okay? And then I'll simply putting the bar as well. And the last one is the jazz. Okay, so let me open up a terminal, okay? And school over here so that you can see properly. So now I will say, Lord, restructuring Dodgers. Okay, so these were the previous locks, but as you can see Okay, So this is not food. This is full. OK, so as you can see, we have this fool as one bar is too, and the jazz as three. Okay, So this is how you would do it with Alderdice factoring by simply fighting the value from the using the index's. Now let's see, how can we reduce this number off? Lines on use their destructive. So I'm going to come in this out, okay? And here I am going to say const and I'll declare this square brackets. So remember that in games of object, the structuring we were declaring the Taliban assists, but in case off the restructuring, we have toe are declared the square brackets. Okay. And first of all, I'm going to simply positive city. Now, what I want to do is I want to fetch the 1st 2nd and third index value on I send them into individual variable. So I'm going to stay here simply so full. Then I'm going to hearsay bar and I'm going to say jazz. Okay, so in case of object restructuring, it was looking off for these properties in this object. But in case off Ray, what it will do is it will try to fetch the index according to index. So the first valuable point to this he wrote index, the second value will point to the forced index on the third of 11.2. The second index Okay on, let me simply say this and again we showed City same result here also. So as you can see regarding forwards one bodies to win the jazz astri Okay, So you guys, this was all about the restructuring. Okay, So it allows you to basically reducing the more off line for declaring the individual variables from objects or a vase. Okay, so there is This was all about the restructuring on. I hope you were able to understand on Thank you so much for watching this video. 6. Spread Operator: Hello. Everyone on in this. Really? If you're going to understand what a spirit operators in tax on, how can we use it? So basically spread operatives in text allows you go fetch the elements from the variables such as our A string and even the object says Well, so let me show you by example. So first of all, I'll hear create a file called us spirit Operator. George is okay. And let's say I haven't had a over here called as everyone. Okay, which is holding values are just warn to entry. Okay. No, the way you can make use off spirit operator is resting place saying let me show you by example This index for it is triple dot on the your trouble with this today. Okay, so let me to save this. Let's go to the terminal on this particular fight. So I'll say North spirit operator Dajae. So as you can see regard, they weren't 23 Okay, So what this index is doing is it's simply taking out the values from this area and spread it over here. Okay, so it just printed 123 Okay, Now what I want to do is Let's suppose that I have another day. Cordes Const Are they do B J? Sick weirdo for five and six. Okay, now let's I want to create Thurday using this forced to always so I can simply say concert a tree equal toe I can spread over the other one. Okay, then I can spread over all the values off the radio, and that's it. That's all I need to do. So let me just console log this as well. Okay, let me simply say this on down this file. So as you can see, I got it. Artery, which holds value such as 1234 which belongs to the 1st 1 Okay, so it is spreading over here, and then we have 456 Okay, which belongs to the secondary. Know, if I was not using this spirit syntax than what would have happen is that it is going to simply, um, put this whole array instead off values over here. So this word form on estate. Okay, so let me show you. So, as you can see, this is your main today. And instead of this, you have this whole array. So this is the everyone on. This is the radio, but that is not what we want, right? It is creating a complex data structure. No. One more important thing about the spread operator is that along with the spreading values , it always make a copy off the sore. So, for example, here, the sources. Everyone on here, The sources are there too. So it is not going toe. They're friends this way over here. Okay. It is always going to make a copy. So how it is beneficial for us. So whenever you make a copy to a new area and if you make changes to January than it is not going to reflect on the old one, right? So that's also ended one days off this pretty operator. Now, let me this also show you the example how their friends creates the problem and it's no legs spread. Operator is mainly for solving the difference problem. Alderdice spreading out values. But it is also creating a copy off those sores. Okay, it is not going to the friends it. So let me show you by example. So I will come in this out, okay? And let's assume that we wanted to keep the other three as the other one. So the one means to do this, which is simply assigning the everyone podiatry. Okay. And let's suppose if I change the area tree on, push some other values such as six over here on. Let me simply print both off the area. We're here. Okay, So I'm going toe for India. Where one as well as theory three. Okay, so they're going to save this. Go to the terminal on if I run this particular file. So, as you can see aboard the array holds the same value. That means the six eyes post toe the area one as well, even though I just pushed her to the rectory. Now, the reason this happened is because this is creating a friends to the array three. Okay, so it is not creating a copy offered. Now, one ways to solve this problem is by using the A one dot slice matter. Okay, So what this will do? Is it instead off for a friend singer? They want to the territory. It is going to make a copy off the area, one to the other three. So let me just around now. So as you can see this time the everyone is holding its original value, which is 123 only. And since we pushed the six value to the other three, it is holding 123 and successful. Okay, so, no, I am going to somebody comment on this line. Okay? And instead of slice matter, I'm going to make you love the spread operator, which is everyone okay on Let me the sport do triple dot over here. And magma tried to run this again. And you will see that again. The everyone is holding its original values, and the tree is holding 1236 Okay, so that means this spread operator always makes a copy off the source instead of creating a difference. Okay. Okay. So now that we have understood everything about the arrays, now we will understand. How can we work with the object using the spread Syntex? Now I'm going to make it off the same object that we used in the previous video, which was this one. Okay, which is a user object and holding some of the properties. So let me just simply call this as user one, okay? And let's assume that we want to create a user to object. We told the same values. But I just want to change the name from David to John. So let's see, How can we do this? So here I'll say user toe, which is equal to user one. Okay. And I want to change the value as user to dot name, equal toe John. So let me just console of both off this. So he writes a console log. Use that one, which is user one over here. Okay, on. I'm going to console along user toe as well. Okay, Now, let me open up a terminal on school. Don't. Over here on. Let me just put on this fight. So now you would see that the user one named property is overrated with the John. Okay. Even though I only apparently user to object. So the reason this happened is because user one is being created as a reference to the user to object. Okay, It has not been covered, so let's see, How can we copy this? So the one way is to make use off the object, the signature, so I'm going to simply say object, not a sign on I B is their target object where I want to copy the object. Okay, so their target object issues there, too. And this source object is the user one. Okay, Now, if I run, leave this fight again. You will see that the original object, which is user one, is holding the same name property with this debit and their target object updated. The name property is John. Okay, Now, let's see. How can we basically do everything using this print operator that we're doing over here? Okay, so the idea is to make simply a user to object, and over it the name properties, John, using the spread operator. So I'm going to come in this out, okay? And here, I'm going to say, const user toe equals to object. So first of all, I'm going to spread away all the properties off the user one Okay on. I want to update the name. Okay, so he rides. His name is John. Okay, on Let's I want to add extra property, which is gender, Okay. And I'll call your desk meal. Okay, Now, this name property will be overrated in this user to object because we're spreading the all of this property over here on this name, Robert is already present. Okay, so it will be overrated. And since this gender is a new property which is not present in the user one object so it will be simply I did for the user to object. Okay, so let me just write good on this again. Let's see what the result of the gate. So as you can see, the original object is holding the same values. And the new object has the Jonah's new property. Also, it has the gentle property that we I did over here. OK, so as you can see how easy it is to our makers off this print operator, OK on simply add some properties to it on. You can see that even though I know what I did the name property, it is not being overrated. Toe the user. One object because you're this creating a copy of the user. One object, nor did their friends okay on and you can see instead off these three lanes it is the court guard converting to just sing aligned right on. In fact, there should have been one more laying for riding the gender over here. Okay, So in fact, the four lines are converted now, so just single line. Okay. So as you can see, how easy it is to work with this spread operator and how it basically is the least spread over the values again from the terrible, such as object. But as well as strings on it is going to create a copy off the source instrument. The difference. Okay, So you guys, this was all about this spread operator on. I hope you were able to understand on Thank you so much for watching this video. 7. Promise Vs Async await: Hello, everyone on in this video, we are going to understand how they think of it before with the promises. And how can you work with the single right? OK, so I'll just explain you by example. So let me this create a file over here called us. You think of it. Okay? And you can name it, whatever you want. So first of all word I'm going to do is I'm going toe create a promise which is going to guide result after three seconds. Okay, so those three second can be any icing task in the world. Example such as an a p A call to us over which is taking some time to get the response. Okay, but here, I'm just going to make it off the set time old method which is going toe simply return the result after three seconds. So, first of all, let's create the promise. Okay, on, we're going to work with this promise. First on, as soon as we're done with the promise, then we will move one video single bit. So there you can clearly on the understand the difference between the think of it and the promises. Okay, so for stole here. I'm going to create a promise card as display message. Okay, so there's basically returns, uh, new promise, Okay. And the force argument is always result. And the 2nd 1 is Did eject Okay on. I'm goingto make use off the September method over here, so I'm going to simply societe mode. OK, so this receives a call back, so this called Big is going to run after three seconds. OK, so here we specify their timing milliseconds, hands 3000. So here I am going to simply it is all the promise. Okay, So I'll resolve with a message which we will get as a parameter toe this particular function. Okay, let me to speak straight over here. Now, The way you can simply work with the promise is by calling this function okay on, you will get it, then call back. Okay. On inside of that called callback. You will get the dessert as soon as this promise is fulfilled. Okay, So, in this desert, let us simply console log this popular dessert. Okay, on as far as the pedometer is concerned, let me just simply pass Hello. Okay. So hopefully this makes sense. Now let me open up terminal that I'm going to simply say north unsinkable torches. So you will see it right? After three second, we will get out of my search. We just Hello? Okay, as you can see now let's assume that we want to bring more message. Let's say we want to make more vehicles, OK? Once we have this result. Okay, So the idea is to only make another promise, Saul, when the 1st 1 is the result. So the way you can do it is by running your task in this call back only, OK, right. If you do anything right after this, it is going toe ground radar. We write, for example, let me just simply print any log and let me just employed on this file, okay? So, as you can see, this is printed right over here, because this task is running a synchronously on. This is the callback which is executed when this task is done. Executing right? So when you took put our second card in this callback only. Okay, so here I'm going to simply say again, display message. And this time I'm going to pass death. Okay, so again, we will get it, then called back. And then again, we'll get the dessert. Okay, so here also, I'm going to simply console log the results. OK, on in sort of this call back. I'm going to make another call to this function. Okay, on. Let me to simply the messages Wassup on. We'll get the results over here. OK, so now what will happen is first of all this promise with lexical on after three seconds will get the hello. Then again after three seconds, will get did there. Okay. And then I'll get after three seconds, we'll get the What's up. OK, so let's just try to on this now. Right? So we got all of this three message, OK, But the problem with this is that we are basically and bringing to the callback help problem. Okay, on this is one of the biggest problem when working with a singleness task in javascript. Okay, so you end up being in called back. Hell, right. So let's say you have five more calls, right? So just imagine what kind Of course it would look like, right. And if any of the promised fails, then we need to up like catch, block, toe each and every promise. Right? Because we never know which promises going to get rejected. Right. So what do we need to do? Is we need to apply catch block. Okay, which receives the other object. Okay. And we need to bring this era right over here. Okay, ATM. It'll do this for each and every promise called. Right? So let me this cop it is pasted over here and be stirred over here as well. Right? So now you can see that how are court is looking? It is basically ended up in the callback. Hell, right. So this is not a reliable court. Okay, so the a think of it, keyword basically allows you to work with the promises on it makes your court more readable by making your court look very cynical nuts. Okay, so this is off course looking isn't gonna score right, because we have a lot of call backs over here, but like to see how can you work with the think of it on, do the same thing over here. Ok, bring the same message is okay. So remember that the thing of it works with the promises only. Okay? So, first of all, I'm going to create a function. Okay, so for example Const my function. Okay, on in this function, I'm going to call this promise display. Miss it. Okay, so the way you can call the promise with these Think of it. Keyword is by first awful writing the overt keyword. Okay. And then you need to specify your promise, which is display message. Okay, on off course it is expecting an argument. So I'm going to pass the hello as well. Okay on. Always remember there to make use off off key word. Your function. It's to be a sink. OK, so wherever you're writing the await cable, your function, it's to basing. So I'm going toe four days. Think keyboard over here. Okay. And I can simply get the result were here like this. Okay. In fact, what I'm going to do, I'm going to declare of it. Results over here, which is going to be empty. String is off. Now on. I just get saying this result of this particular variable. Okay? Now, what I need to do is simply again called the display message, okay? And just passing the my sister. I want to pass. So here this time I want to pass there. Okay? And I can again simply assigned the desert. So this particular variable Okay, on again, I can do the same thing with numerous activities. Wassup. Okay, now important thing to note here is that this is in call Will only exclude once this is fulfilled. Okay, so that's the beauty about the thing of it. So the of it is actually going toe stop the control flow moving forward until and unless this particular promise is either results or reject. So that is the most important thing about the thing of it. Hence we don't end up in the callbacks, right? Because this is basically waiting until and unless this problem promises resort. Okay, so are controlled flow is not going to move forward. And let me add the console log over here so that you can see properly the sequence off execution. So here I bring the result over here. Simply copy this, print it again and print it again. Okay. And let me simply command the promise out so that you can, of course, see properly. So let me to save this on alleged Go with air terminal. Okay, clearly console and run this file. Okay? And I think I forgot to call this function. So let me just simply call dysfunction as well Over here at the bottom. Now, on this file on hit. Enter. So let's see, What do we get? We got the result as hello for civil over here, then regard there. And finally we got be wassup. Okay, Now you can yourself compare the court difference it brings. When we woke the promise and when we worked with the think of it, this court is extremely straightforward and readable to the developers as compared to this one. Okay, so you can imagine how easy and efficient it is to work with these. Think of it. Keyboard rather than the promises. Okay, on. Even if we talk about the other handling it is so much better in case of a single bit as compared toa the promises. As you can see here, I have to apply the catch block to each and every promises, right? Okay. The reason is that any off this promise can get rejected, right, But in case office innovate, the overhead keyword throws theater as an exception. Whenever this promise is rejected. Okay, So what you can do is you can handle the exception using just single try gets block. Okay, so let me show you what it looks like. So let me. I did write gets blocked as well on. All I need to do is simply bring theater over here in the console log. Okay, so let me just do it on. Let me just take everything from here, okay? And pasted over here. So now if any off this promise is rejected, then it can be simply handled over here in this sketch block. OK? So as you can see how good your core looks when you work videos, think of it as compared to the promises. Okay? And let just even try. Do it on a scenario to show you the other case. So let me just come in this out. So let me this even show you an example how this cage block will be executed. So let's on this particular promise. My number divorce up messages saying we need to basically reject the promise. So here I can simply say if the message is required. So what's up then? Simply rejected on simply say something. I went, but all okay. And here are also I'm going to add it in statement so that the court blocks is not executed for that. Okay, so let us investigate this large garbage terminal on dry food on this fight. So you will see that force will get the hello message, then they there, And as Souness divorce up, our task is as executed will get there. So, as you can see, we got there on it is here in the something went wrong. Okay? And we're able to do this bites in playing a single catch block, okay? And in case of promise, we had hoped, like, edge, block to eat in a very promise called. Okay. And one more thing I would like to tell you about the think of it. Keep it. Is that the await keyword off course expects the promise. Okay, so in our case, it is returning a promise. So it is working. Fine. Okay. So you can apply the over a keyboard on Lee to do two things. The 1st 1 is if you're function, is returning a promise which in our case, it is doing OK. So the display messages returning a promise or your function should be facing function if it is in order turning a promise. Okay, So remember these two cases, Either your function is returning a promise or your function is an amazing function. So let me show you by example. So let me There's declared a function over here quoted as greetings on, let me make this function as a sink. Okay? On it is going to simply return, for example. Hey. Okay. So now I can apply the await keyword toe this getting function because it has these in keyboard with it. Okay? And remember, I just told you right now that either the function has student and a promise or it has to be anything function. Okay, so let's just rightto apply the await keyword. So this greeting function okay on, let me simply get the result here and let me even consume lobby. So now I'm going to execute this, But before that, let me just simply them comment about this court blocks so that we don't get any sort off better. Remember, this particular promise is executed. Okay, So that means this Corby their dominant on on this fight says agency regard the hey my sexual here, which is printed over here, right? So now let's understand what special difference does the ace in keyword makes to a normal function. So animal you apply is in keyword to a normal function, and it returns the value than this value is not return as a simple value. Instead, this value is returned as a promise. Okay, so what it will do is it will try to always result this particular value as a promise. And that's the reason why you are able to apply the orbit. Key word on the matter of the fact is, if you are using this hazing function, then you can also simply say great things. I thought. Then you can apply, then over here. Okay, so the reason you can do it is because this is basically resolving as a promise. Implicitly, you are not able to see it. But the Zinke what is doing that? Okay, so let me one show You Okay, so I'm going to simply quickly console log the reserved over here. Okay, Now let me go to their dominant and run this file. So as you can see, we got the value right away. So there is. This was all over these. Think of it. Keyboard on. I hope you were able to understand this on. Thank you so much for watching this video. 8. API Overview: Hello, Everyone on in this video. I just wanted to give you the over you off the a p a that we're going to build. So as you can see on the screen, we have basically user Rabia on the left inside on the product ap underwrite inside. Okay for the user rebate, we have the typical logging in this an EVP. Okay, So as soon as the user log in, he'll get an token called less Jason wept Okun or jwt token. And we will use this JWT broken as an authentication step before allowing the user to exist the product resources. Okay, so we have videos product eBay, such as supposed to pay for regulating the product, getting the list off product with pagination, getting a product by 80 operating a product bitey and deleting the product. Buy it. Okay, so these are the a p a that we're going to build on. Let me just quickly show you the architecture of the A B I that we are going to implement. So, as you can see, this is the PR conjecture on that we're going to implement. So at the bottom, if you can see there is this That exclaimed. Okay, so you're wrestling can be anything. It can be a Web Rosell native and or device or the IRS device. OK, any sort of claim that can interact with the extractive protocol. So as soon as they exclaimed saying the request, it will be handled by the roads in our Norges server. Okay, Now, for on the roads, we will make various decisions. Okay, So let's say you want to sometimes want to validate some off the stuff before proceeding for the suggestive, illustrating the token, okay? Or maybe validating the request data, presenting the payload or even in the credit programs. Okay, so they're a couple off checks that you want to perform before pursuing the request for the so For that will be implementing middle bed. Okay, so your middleware will be responsible for validating the request data as well as validating the token. If their particular a be a secured okay. And if not that out will basically transfer the request. They declared toe de controller. But if you want to have some checks, then we will pass it to the middle where Okay, so middleware will perform all sort off checks on if any sort of validation fails, then it will basically signed this other back to declaim. Okay. And if the validation is success, then it will basically transfer the request to the controller on here in the controller. We're going to prepare their data that is required by the service. Okay, Andi controllable. Basically call this service and said this is very you basically write the business logic. Okay, so here, civilian track with the database to get the data on service will then transfer this data back to the controller and controller will finally send the response to decline. Okay, so this is the end one flu that we're going to implement. And if you're wondering, why do we need service instead of writing the business logic in controller itself? So let me just tell you that as of now, we haven't implemented anything. But just for the sake of answering this, I would like to tell you that the controller is nothing but and called back to out. Right? So this has access to the request response Object. Very service are basically normal function. Okay, so once you write your business logic in the normal function, but you can do is you can basically reuse this particular rock logic. Okay, but if you would have returning in the controller, you wouldn't be able to reuse it. OK, since those are not normal function, those are callback function which has access to the request response. Object. Okay, so if you rate our business lodging in a normal function, it can be reused, OK? And you will not violate the dry principal villages. Do not repeat yourself. OK, so it will help your Lord because ah, lot off service will call internally other service to get the data. And let me just explain you example how this reusable service is going to help us. So as you can see on the screen, consider this example where we have to a be a The Force one is to get the user detail, and the 2nd 1 is to get the order detail right off a particular user. So in the user to daily prayer. What you do is you basically ask for the user ready in the part perimeter and you simply go to the user details office and first do data from the database and give response back to the client. Okay. And in case of order detail, we basically want to face the order detail as well. Is the user details? Right. So you first of all go to the order details service throughout Controller. OK, on Dhere in the order Little service, you basically interact with their database and get the order detail. OK, but now you also want the user details along with the order detail. Right? So one way that you can do it is by simply again hitting the database and fighting the user detail again. Or what you can do is since you already have returned your business logic insert of the user detail service which is simply a function residing in a particular file. What you can do is from the order little service you can simply call dysfunction. Okay, This service is nothing but a function, so you can simply call this function pause. The use already on that particular user detail service will return you the user to tell itself So what you have done is here. You have just to use the existing business logic. You haven't wrote it again. Ok, so this way you are basically reusing the existing piece off court, which is a good practice. OK, so your guys, this was a brief information that I wanted to give you about the way that we're going toe buried. So that's it for this video on. Thank you so much for watching this video. 9. Setting Up Node.js Server: Hello, everyone on in this video, we're going to set up a basic Norges server so that we can get started. So, as you can see, I'm here on the terminal and I'll simply create a folded over here called as North hyphen Abia. Okay, on inside of this, I'm going to simply, first of all, initialized the packets, tortoise and file using the end, innit? Common on it will last members off cushion. So for the Packers name, I'll keep it as an or have an e p a. I'll give the was honored as it is description as it is on for the end crippling dial Cesar were door Jess. Okay, Onda off. I think the rest of the things are fine. Just hit. Enter on. As you can see, we have the package Dodgers and ready on. What I'll do is I'll install a couple off packages off now just to get started, so I'm going to install off, gets called as express. Okay, This is a reference book for the Norges, and I'll make use off another package called as dot envy, which can be used for setting of environment variable in Norges. So let's just hit. Enter Andi. This will basically install the all the packages and let's open this folder in the via scored. All right, on. So let me just open up. The package isn't so. As you can see here we have the daughter and we and the express on what I'll do is I'll festival create Assad word RJ's file over here. Okay. And let's start setting up this up also here. First of all, I'll say const express equals required express. Okay? And then I'll basically create our instance often. Expresso here and seconds. Toe physical to express. Okay. And here I'll simply say I have dark. Listen. Okay, so there's basically expect a port. So for the board, I'm going to simply say const port equal toe. First of all, I'll try to fetch it from the environment Variable if it is present. Okay? And if this is not found, then I'm going to make you suffer default poor to call this 3000. Ok, now, how do you get the environment variable here in the Norges? So if you remember, we install this package called. It's not envy. So let's make use off that. So here I am going to first of all, required the daughter envy. So here I'll say the choir Doherty Envy. Okay, Onda, once you basically called the daughter in without conflict mental, what it will do is it will basically look for filing your project folder called this dart Envy. Okay, so let's create this on board A with variable. And if I know we're here, this producer by kids will make it available in the process. Don't envy. And that particular variable name. Okay, so let's define this sport on for the value of the port in the environment. Variable. I'll just simply cited as 3002. Okay, Ana. Now, since we have simply called the doctor in without conflict, this particular variable will be available from the environment. Variables. Okay, so I'm going to simply pass this particular port over here on here will simply get a call back. Okay, so here I am going to simply second so log, and here I am going to make it off the back, takes on here, I'm going to simply say server listening on board, and I'm going to make use off the template variable and specify deport over here, right As simple as that. So let's just save this now on. Let's try to run this pile so I'll head over belittling now. Okay, on simply undefiled by north side Ward or two years. So, as you can see, it says that we're listening on poor 2002. Let's head over to deport 3002 in the process. So now here, it says cannot get slash. Because as of now, we haven't defined in this sort of route. So, like, just define So what I do is here. I'm going to simply say app dot Get on. This is the road road, okay? And in the callback, it basically has access to the request object, response object and the next function. Okay, on what I lose in this political big, I'll simply say responds dart sand, and I'm going to say hello from north. Settle it. All right. So let me see if this now on. What I didn't need to do is I need to start this over again to see the changes, right? So let me start it again, and there's going to the Broza fresh the app. So as you can see regard this message and Every time you make any changes in the file, you have the facility. Start this award, toe. See the reflector? Tinges of what? Here. So what? We lose instead of restarting this about again and again, we're going to make use of the library called doesn't hormone. So what it will do is it will basically look for the changes, and it will automatically start this. Edward. So what I'll do is I'll first of all installed in order one as a day of dependency. So here l seven PM stall high friendly for their dependency on the name of the library, which is normal. Okay, on once this is installed, we're going to create a script in the packages and file, which we're going to use to start this hour. Okay, so let it install. OK, so as you can see, it is done installing. So now what I'll do is I'll simply head over to the package store GIs and file. And as you can see in the death dependency, we have the notable. Okay, so, first of all, I'm going to create start script over here. Okay, So here I'm going to simply in this start script going to say North Settler Dodgers. Okay, so this will probably you will use in the production. But for the death, we want to have the life eating just reflected on the fly. So here I am, going to simply say Norman said were gorgeous. Okay, so for the 11 moment, we're going to make use off this brutal A script. So now what you gonna do is you can simply say npm done there. So as you can see, it has started these Edward Gorgeous using normal. And it is basically watching your project folded. Okay, so let me rephrase the application so that I can show you this running. So, as you consider is running knife, I make anything just in my file. For example, if I change the message from hello from Nord a p s Edward And if I simply save this, I believe those are all I need to do is simply the freshly browser to see the changes. Okay. I don't have to restart again and again. And if you have a look at the console, then as you can see, it has basically started. This are due to changes. Okay, so this was just a basic set up off our North, sir. Rap on. We are going to further add more things to it. But I just wanted to get you started in this particular video on I hope you were able to follow along. And thanks so much for watching this video. 10. Express Middlewares : Hello. Everyone on in this world of you're going to talk about the middle ways in express. So it is one of the most important concept to learn whenever you're working with the express in Norges. Okay, so let me head over to the official documentation so that I can explain you clearly. So if you basically search for express, Really? Where? And this is the place that you want to visit, OK, so as you can see here, it says the middle where our function that have access to the request object, response, object and the next function. Okay, so with the help off next, you can basically call the next minute. Where? Okay, So as I said, these are just basically a function right. So let's see what kind off middle where you can implement in the express. So you have application level middleware, out level middleware head of handling money where built in middle us and third by the middle. So OK, so we're going to implement all of them in our application butts. Let's have a look at the basics. So if you talk about the application level middleware deserving, we deliver that are defined on your app object itself. Okay, so let's just see by example So let me just go to the court weighs and here we're going to create our own middle so that we can understand it. Really? So here I am going to simply say const my middle way and it is going to be function on. As I said, it has access to the request object response object and the next function. Okay on Dhere. I'm going to simply concerned loggers off now. Hey, Wassup. Okay, so this is the message I wanted. Log on the way. You can use the application level. Middle varies by simply saying abduct use. Okay, so remember that this is the use method that you want toe. Make use off for implementing application level middleware on here. I'm going to simply positive my middle. Okay, so now I have written the request comes to ourselves over this middleware is going to run because it is defined on our group object, which is up object itself. Okay, so every time you get a request, this model that is going to execute OK, ok, so now let's try door on this on Let's school to the browser on Goto 3000 to port. Okay, on which application is earning. But as authorities simply lording it is not doing anything. Okay, but let's head over there. Three million. Say, what do we get? So as you can see, we got this message called us. Hey, what's up on the console? Okay, so that means our Middlebury basically ran, but the control Floridian move forward on. We didn't go out this particular message, which is hello from, nor debates over. So why is that so? As I don't do that with the help off next function, you can be silly called the next middleware. So don't move forward. Would you need to do Is unity basically called the next function over here? Okay, so let me say this now and let's go to the browser. Now, As you can see, the controller basically move forward on BBC regard this message from here, okay? And even if we have a look at the consulate and as you can see, we have this middle very message, which is hey, wassup. And we also got D message over here. Okay, so in this particular function, you can do any sort of operations, such as checking the payload or validating token or any any sort of operation that you want to perform before moving forward. Okay, so that's what the middle where are for Okay, on if we talk about their weaken Montek. So as you can see, we can mounted on the app object itself. Okay, Now, let's suppose dirty one door on this model on live in this particular route is hit. Okay? So instead, off mounting here on the app object, what you gonna do is you can mount it on the part itself. Okay, so that's also called less abstract middleware. Okay, so what? I lose and simply basically removed this. Okay. On. Instead, off mounting on Abdus, I can mount it on the part itself. Okay, so here in the second argument, I'm going to basically call my middle. Well, okay, so you will see that this time also will get this. What's up? Message. And then we'll get this pretty response to the browser. So let me go to the browser, refresh the up again. So as you consider guard this particular message and if we go ability criminal, then we got this little message with just here. What's up? That means our middleware basically ran. Okay, so there. So you can basically amount the middleware on the part as well as on the app object. Okay, so this is your basically application level we deliver. Then you also have the total level middleware. So these are basically similar to the application level Middle where their differences there they're mounted on the express door. Robin stands instead of the express itself. Okay. And we're going toe use this road level middlebury in the upcoming videos. So all the level middleware will help you in writing the modeler crowds. Okay, so this is your or the level middle. Well, then you have some other middleware, such as other handling me deliver. Okay, so this is a special middleware in the express where it has access to four arguments in start off. Three. Okay, On the extra one is the other object itself. And remember that this has totally force argument for this middleware Taubate recognized as are other handling middleware. Okay, so let's try to at this now, okay? In our application. So the bottom would lose and simply had other handle middleware. So let me add the comment here as well. Middleware. Okay, so this particular middleware comes handy whenever you are trying to forget to catch any sort off error runtime error in your application. So that, producer added, will fall back to this particular Adam Middle. Where? If if it is defining your application, OK, so it's a good idea to define it over here and here I am going to basically modify this responsibility. So this looks fine response towards status that this is the state of scored off the street response on. And instead of the sending the message, what I would like to do is I would like to send in a particular standard format which we're going to define in the upcoming videos. But just for the sake off, writing it over here, I'm going to sink this estate us as 500 over here. Okay, so I'm sending the response traitors in the response body also, Actually, it is not required, but it will be very handy for our client who is consuming the Abia to have the status in the response body also for the message we like to fight to the message from the other object. All right. And for the body. I would like to keep it simply and empty objectors off now. Okay, so we're going to use this standard response for Mitt. Okay, which will understanding the upcoming videos. But as of now, you can see that this is how you can apply the global error handler middleware. Okay. Next, you can basically have make use off some building middle bits such as bolivar, for passing the content. Type off a petition, Jason on middleware for parsing the content type off form, you are included. So before this particular express version, you basically had to use the body parts of a package. But now with the for dort 16 or zero, you can basically make use off the built in middle wears. OK, so we're going to define this so that this head over to the court based on First of all, I would remove this custom middleware like we just defined removed from here as well. And here I am going to simply either comment. So here also request they lord model. Where on here. I'm going to add those middle well, so here and abduct use on going to say express door Jason. Okay, so this will help in parsing the content. Type off applications isn't. Then I'm going to also apply the Express. I thought you are all included, and here I'll pass the extended property as true. Okay, so this particular Middlebury is going to help you in passing the for mural and coded data . All right, on that side for the middleware for handling the request. Payloads. Then if we move forward, then you can use make use of some tired party middleware. Okay, So what we are going to do is we're going to make yourself tired of party. Middlebury called discourse, which is used for cross origin request. OK, so whenever you're building, there s declared isn't very important toe Have your server course enabled. Because if you don't enable your server with the cars, what will happen is that you will get added something like this. As you can see on the screen, animal user tries to make any pay call from other domains from their your saddle up his horse state. Okay, so you will get this kind off other if you don't have the course enabled on your server. And since we're building that s t. P a and arrested. They will be consumed by many claims that as many domains are even the native clients such as the Android or the IRS device, it is very important to have your subtler coursed enabled. Okay, so let me simply first of all installed the packet. So here in the terminal, I'm going to simply say npm stall course. Okay, Onda, remember that on the other terminally ill we have this adorning on, I'm running this particular common in sort of the integrated on middle of the year school. OK, so if you have a look at the packages and as you can see the courses and started no and simply basically required the course, Okay, so here and say required course ongoing doesn't be registered the scores using the ab not use matter. So, like missing bliss abhorred use cars. Okay, so this is all you need toe due to configure the course. Okay. And now we won't get any sort off error whenever a user tries to access our server or the rest a ps from other domain. Where are less debates hosted. Okay, So you guys, that's it for the understanding the basics off the middle where and using some of the target by the middle. Where is in our application on I hope you were able to follow along on. Thank you so much for watching this video. 11. MongoDB Connectivity: Hello. Everyone on in this food of you are going to basically connect our application with the mongrel every database. So for interacting with the mongo db, we are going to make use off a library called as mongoose. So mangoes is an order am library, which is object data model, eh? Pretty so. Even though the nose equality databases like mongo DB doesn't require your toe are designed the database schema off front, but still the help off mongrels liberally. You can define this schema using which you will store the detained the collection. Okay, so the schema will basically help you in restoring the consistent data across your database . OK, but as off now, in this really of years is going to make our DB connectivity to the mongo db. So what I'll do is foster fall. I'm going to install a package called us Bongos. So here and simplest and payment stole mangoes on by the time it is installing, what I'll do is I'll create a folded over here called this database and insert off this I'll basically create off finally called us connection gorgeous. Okay. And instead of this connection or just what I'm gonna do is I'm going to first of all required among goes. So he'll say, const mangoes equals required among those. Okay, And I'm going to simply export or function. Okay, so here, Alzamora Lord Export okay, on this is going to be narrow function and instead of this will write the logic for the connectivity. Okay? And as you can see, this package installed so let him close their terminal. And here I am goingto make use off the connect matter toe connect to the database. So here l Z mangoes don't connect. So this basically expect some arguments such as the U N for the database and the extra options. So forfeiting the Urawa Basically, Fetchit from the environment variable. So here I'll say process dot envy dot db underscore. You are okay. Let me define this particular day. Be orderly In the end, we file. So here I am going to someplace or db Oral equals on the way you can define them are going to be your Elizabeth saying mongo db Collins life slash local host slash the name off the database. So, for example, we want to name our database as a p A baby. Okay, so they're certainly be yours. And for the second argument, you can pass the various option one off, which is the use new your Bill Parcells. So you need to pass it for the New York version off monger TV. So just implicit rule here, Okay? And since this connected matter basically returns a promise, so I'm going to make use off the keyboard over here, okay? And to make use off the over keyword, I need to make this function. You think? OK, on what I, Lewis toe handle the error. I can simply rapid inside off their try kids block. Okay, so let me move this statement in sort of the try. All right? On in. Case off any other, I can simply console log database connectivity header. And I'll simply bring the air over here, okay? And I'll simply true it over here. So it's a throw new error, and I'll pass the air optic itself. All right, So that home So what is calling this matter? You can basically catch the other. And once this connectivity successful, like in simply second, So log dws connected. All right, so this looks good on. I think they're good to go. All we need to do is simply call this method. So I'm going to save this now. And let's head over to this hour. George's So here in this airport, George, a spell where we are initializing r e p s our work. We also want to connect to the database. So first of all, let me require this fight. So here also, Const. Debbie. Connection equals required w slash Connection. Okay, so now I'll basically called this matter. So here I am going to First of all, I'd be comment as the beacon activity. Okay. And I can simply certainly be connection. Okay, So now what will happen is this will basically call this method, and it is going to make a connection. All right, so let me say this and let's head over to their terminal and see what do we get? So as you can see, regard the message as data is connected, let me when restart the server so that you couldn't see properly if I don't end, came around there. So we should get dismisses. As you can see, it says that the disconnected that means it is done successfully. And if there is some error. You will see that in the control is well, because we have some blueprinted the connectivity at over here. So just for the sake of printing the other, for example, if I don't pass the u. N. All right on, If I simply say this now, alerts had ordered the eternal. Then, As you can see, we have this other printed over here. So it says database connectivity, either. Which we have printed over here. All right. And it is basically issuing What kind of Federated? All right, so let me just do the changes. Let me see if this now on had a work of the bottom. The next agency. We have this success messages that I was connected. So that was that's it for the database connection on. I hope you're able to follow along on. Thank you so much for watching this video 12. Product Model & Schema-Mongoose : Hello, everyone on in this video, we're going to basically create immortal for the product. So 1st 12 order Lewis in sort of this data bus full that I'm going to create off for the record as models. So this is where we will or define various models off our databases. So first of all, I redefined the product model, So here, I'm going to simply say product modern door, Jess. And here I am going to first of all, required the mangoes. Okay, so here l z required mangoes, Okay? And I'm going to simply export the model. So he ran. Same moral dart export equals mango's not model. All right. And instead of this, you have to pass the name of the model. So far, the name. I'm going to keep it as product on. In the second argument, you have to basically specify this schema. Okay, so it basically defines what kind off data. What type of data should be inserted in this particular model. Okay, so what I'll do is I'll first for the finance schema. Korda's brought up schema okay on going to define it just now. So here I am going to simply say const. Product schema equals new mongoose dot schema. Okay. And inside off this it basically takes an object on here You can define the field's off your model. So for the product, we basically want to have the name prize and LeBron so he Reagan subleasing name on this will be off type string. Then we will have the price which will be off type number on that last will have the Bron, which will be off type string as well. Okay, So this is how you basically defined the model on past this schema to their particular model. Okay, so now what you gonna do is in the upcoming videos will make it off this mortal on. Well, basically, store the data into this particular model, okay? And we can do one more thing over here, which is to pass another option in the second argument. OK, so here you get past various option So one off, which is the Times Times. So if you passed this as true than what it will do is it will automatically store the created at on the operated at filled insert off this particular model. That means diva never the record is inserted in sort of this particular model than mongo DB will automatically add are created at date. Okay, for this particular record on, if this is a breaded mongo, DB will automatically update the date as well. Okay, so it's quite helpful. Toe have the date related information for each and every record. So the guys that's it for the are defining the model on. I hope you're able to follow along on. Thank you so much for watching this video. 13. POST API: Create Product: Hello, everyone. So, in this road of your going toe, create the A P I for creating the product on, we're going to create its routes controller as well as the service. OK, so now what I want you to do is tow download two pools. Basically, the 1st 1 is the postman. This is for testing the FBI's okay, on it is one of the most popular tools, so you can get it from get postman dot com on the 2nd 1 is the g A Y tool for the among. Would be okay. So this studio treaties depended one. Okay, this comes with one month free trial, but it has some once you want another one's features. But I would recommend you to install this one. Which is the robot? Pretty. It is completely free. Okay, on it has some basic functionality that you need. Okay. So you can basically interact with your database using the video, you can perform crowd operation over here is Well, okay, so when she installed deportment, it should look something like this. Okay, so it is loading up on If you install the war treaty, it should look something like this. I guess I'm opening that also. So this is how your robot ready should look on. This is how your postman will look like. Okay, So before proceeding further, please install the struggles. Okay, so now alerts posted further with building the FBI. So first of all, what I'll do is I'll create the road for handling the product related e p eyesight. So here I am going to simply say app door to use. And I'm going to make use of the EU's matter. Okay, on here, I'm going to define it out. So I lend it olders slash ap a slash b even slash product. OK, on the reason I've named this in this particular former it is It is basically standard to start your rapier with this life. She pending me. Okay, Then you can name the your papers and with the one we took me three. Okay, So, basically, for example, if you make majors in just individual, right, so at least you have the Viva note for back supporting existing users, right? If you will read existing Abia, then all your existing user who are using the previous Abia that eBay will be broke, right hands we basically name it like this. Okay, so I have basically capped the you are less slash CBs slash given slash product. Now, instead, off handling it over here with the request response. Object. Okay. Just like we have handled the road. Rode away here. What we'll do is very model arise are accord with their outer middleware. Okay, so as off No, we have defined the this base part on the app level middleware, but we will handle this popular thing in the total level. Middleweight. Okay, so what I'm gonna do is first of all, create a folded over here called as adults. And instead of this, I'm going to create a file called as product doubts. George's okay on here. I'm going to first of all, get the Express. All right, on. Once I have this, I can simply get the rotor. So this comes from express? Not okay on. All I have to do is simply say model export equals No. All right, so now that we have this product rolled study, what we can do is we can basically make use off this route toe handle this particular part , right? So, basically what I'll do is simply, I'll say, require adults slash broader grounds. Quite simple. So this particular part will be handled by this road file. Okay. And here we can define various Esther tipping matter such as the outer dot post for the post debate out or don't get put. Delete. Okay. So you can make use of this matters. So as of now, we are creating the post Libya, so I'm going to say not post. Okay on here, I'm going to simply say slash. Okay, So the reason I'm applying this slash over here is that this particular route will handle does route who start with slash ap slash human slash product on that's it. Okay. For example, if your name here as list. So this rotor is going to handle those parts which starts with slash ap slash 31 size broke , slash list. OK, but we don't want to have anything as off now, but you can for the name it over here. Okay, so you can say that you have basically defined your base part on the level middleware and only for the road you're basically handling in sort of the product roads. Okay. And this makes sense right in. Start off writing this last debate slash given slash product Individually, over here for each and every doubt. It is good to define a bass part, right? Because all the product related routes will always start with this route. OK, so this is going to be a common. So we have defined this on the app level, middleware and all the for the road, for example slash products slash list. We really define it over here in their own profile. Okay? And you can repeat it for videos. Models such as, For example, if you create a user model, then you can simply say a PS slash movement and you can create a separate road file for two years or drugs. Okay, so this is how you basically model raise your wrote. Okay, so it's of no where they lose all, basically, simply print out the response over here, so I can simply say just order me responsible. Simply say response dot saying and I can simply say product created successfully. Okay, this is just a response to basically tested out. So now what I'll do is I'll basically go to deter mill on start us that what So here I'm going to simply saying memoranda. Andre will open up the postman, and we're doing arrested over there. Okay, so here I am in the postman. I'm going to select the post Esther Tip immature on the U. N. That we want to hit is a studio p colon slash slash local host slash ap slash everyone slash product. Right. So now if I heard this, then we should get a message. So as against the regard, this message, which is president over here. Okay, product later. Successfully, That means a lot that is working properly. Fine. All right. Now, if you remember the architecture diagram, we basically wantedto have the controller to handle this particular call back. Right, because it is a good idea toe. Have the doctor file only have their doubts defined. Nothing else. Okay, so you don't want to keep any sort of logic over here. Okay, S So what we'll do is a little create our controller file over here. So here and second troller. Okay. And I'm going to create a product controller dot Js file. Okay. And here I'm going to simply export a function. Carla's create product, right? And this function is going to have access to the records and the response object. Okay, that we will get from the call back off this road. Okay, so here, first of all, let me grab the product controller. So here, I'll say const. For the controller equals the quiet controller slash controller. Alright. And instead of handling it over here, what I'm simply gonna do is I'm going to say product controller dot Create product. OK, so now whatever we rolled over here will be handled by this. Okay, So let Megan's and the response from years, I'm going to simply say respond. Start saying on here. I can simply say product Could you do it successfully? All right, let me see of this now and hopefully Trude work. So I'm in the postman. Okay, So if I heard this again, and as against TV again guard the same message. All right, so now from here, what we'll do is first of all, we'll try to get the data in the request. Body said since we want to create the product, we basically need the name brand in the price, as we have defined over here in this schema. Okay? Name Bryce and LEBRON. So what I'll do is I'll simply first ofall try toe print out the request body over here. Okay, so I'm going to delete this on here. I'm going to simply console log the quest body request start body. All right, let's see if we get the date. Anybody. So what I'm gonna do is I'm going to see, like, the body over here selected Jason on going to past data from here. So, for example, if I name the product as guys will shoot for the brand on going to simply say 90 for the price, I'm going to simply say 100. Okay, Andi, if you remember the prices basically number right. So now if I hit this, let's see, what do we get? So in the console, As you can see, this is the log that we printed, and we are getting their data right on the reason we're not getting response because we haven't sent anything in the response. So now what I'm gonna do is I'm going to pass this request body data to the service, and the service is going to interact with the database and create the product. So first of all. Let's create this obvious. So here I'm going to create a four letter cordes. So is and insert off this, I'm going to simply create a file called Eyes Product Service. Okay, so the idea is to not to write the logic over here, which is the business logic. We are going to write it in the product service. Since the product service is going to be a simple function, it can be the used right. You cannot reuse the create product controller function again and again because it's and basically handler. So there are criminal right, and it has access to the records. A response object. You can basically try to reuse it. But the logic that you write will be very cumbersome because you have to detect whether it's in simple function called from another service or another controller, or whether it's an handler request. Coming from there ultimately will, right, so it's better to separate your business logic in this office. So here I am going to simply export a function called us. Create product on this is going to be simply a function okay on. It will basically receive the detained the arguments, so I'll simply call it a sort of his data. All right, on what I'll do is I'll pass this request body to the product service. So let me, first of all, require the products of its over here. So I'm going to send us a const product service according to required. So it's slash product service. Okay, on going to simply call this matters, I answer product service dot Create product. All right? And I'm going to pass the data. What would we get in the request body? OK, so we'll get this right over here in the product service on Dhere. We want to basically insert the data into the database. Right? So first of all, let me require the product model over here, So here I am going to simply say product, which comes from the database fuller slash mortals slash product model. Okay, so nobody uncertainty Rita in sort of the product model, I'm going to simply say let product equal to new product, okay? And insert off this, you have to basically passed the data that you want to insert in the product model. Okay? So instead of getting all the fields and usually like, for example, name from service data dot name and the price equals service that are not price Okay on as well as the brown from the service later, dark brown. So instead of writing it like this, what I'm going to do is I'm going to simply spread away all the fields from the service that object, because the key and the value are the same. Okay, so what I can do is, instead of writing it like this, I'm going to simply remove it on. I'm going to make use off the spirit operator. So here I can simply say service data. Right. So what I basically done is I've spread over the all the values off this particular object inside off this as an argument. OK, now all I need to do is simply call the save method on the product. Okay, so here I am going to simply say product North Sea of okay, on the save method will basically it on your promise so I can make you love the orbit keyword okay on to make use off the other key. But I need to make this function. You think all right, And I'm going to simply it And what what is returned by the same method? Right on. In case of any other I would like to add Try kids block. So here I'm going to add a trike. It's block right? Let me move this over here on In case of any a I can simply say throat new and again past the other object. Quite simple. And I can even I dig in so long over here so I can see is a console log. Something went wrong and I can simply space were buried went wrong So I can Simples is office then I can simply say create product which is the name of the service and I can simply print already at object. Very simple. I hope that makes sense. OK, so what we have done is first of all, we have created DeNoon stunts of the product model past required data and called the save method to insert the data in sort of this model. Okay. And we're basically are waiting over it. Since this returns a promise and they're basically returning the desert right source services ready? All we need to do is simply handle the things in the product. Controller OK? Because the product controller is the one which is going to return their data to the client . Okay, so the purpose of the service to simply inserted it and sort of the database on Britain, the desert to the controller. OK, now, so is this. Create probe is basically returning a promise because it's anything function. I can apply the gatekeeper to it, and I can get the desert in a variable card, as responds from service. You can name it whatever you want. OK on to make use of the keyboard. I need to make this fun chasing. All right, on what I'm simply gonna do is going to remove this log over here on to handle any sort of area. I would like the try. Catch block. All right, on going to move this thing in sort of the try block on in case of any other I can simply for stuff. All see, console log. And here I can say something went wrong, Controller than the name of the controller. It is create product on simply print out the other object. Quite simple. So now what we want to do is we basically want tohave the desert return toe the line. Okay, so we're going to have a standard format off the pattern in material, basically returning the data to decline because it will be predictable for them. Like what sort of data will be returned by this over. So we're going to have the response. Former, something like this, as we have defined in the global Lederhandler, which is to sign these status in the body itself than the message. Like what happened and the body in which will send the data. Okay. So in the response will always have this status, which will hold the state s court of a strategy. Then we'll have the message like, what happened? Something, for example, a product created successfully, Something like that. Then we're going to have the daytime, the body. Okay, So what I'll do is I'll first fully create response object over here. Okay. On, just below this, where our products services getting results, I can simply say responds dot status equals 200. Then I can simply say response Dark message, equal toe. I can simply say product could you did successfully. All right, on that Last weekend's implicit response dot body. This is very sandy data, so I can simply say response from service. Quite simple. And in case of any other, I can simply say here, for example, responses. Status will be 400 for the message. I'll get it from the other dot message. All right. On for the body. I'll keep it as empty as off now. All right, Annette last I can simply surgery Done. Response dot Status. So, for the status, I can simply say responds object dot Status. All right, on then, I can simply say sign and insert of this. I can simply send the whole response object. Okay. So hopefully this makes sense. So let's just try this now. All right? So are so is running. Fine. Let's go to the browser on. Let's try dude on this now. So, as you can see regard this response magistrate is 200 messages product created successfully and inside of the body. We have the underscore i d bitches on mongo db Object Ready, Edited by mongo db itself. It's a unique I d do it in every record. Then we have the name price brown that was sent in the request body on because we said the time stamp as true in the product model, right? As you can see. So that's the reason why we basically have these two dates created at and upgraded. Okay. And this is the another field that this cup by the Mongol, which is double no school to be for the division on, even if you have a look at the robo Thrity. Okay. So I want you to open this particular tool, Onda, If you don't see this dialogue, you can click it over here on simply, double click on this. Okay, on, as you can see here. Is that a pair, Davy? Then you open up the collection. Then if you open up the product than as agency, this is the product that we just inserted. And if you click on this, then you will get our table view. Okay, so this looks more clear on you can even right click on this and symbolically convey your document. So, as you can see, this is their data that is inserted in our database, right? Sorento and flu is working fine. Onda, let's also have a look at the flu. How is it working? So in this hour, Georges we defined a bass. Part of it is slash ap slash weapon slash product. Okay. And we define it over here in the uplevel Middelburg. Then we transfer the handler the rotary middleware. Okay, instead of their ordinary middle where what we have done is we have defined it out. They're type of actually be method. Then VB is really passed this handler toe d create product controller. OK, The clear broken dolar is doing nothing but sending the data to recreate the product service and basically sending the response to declined with the appropriate data and in a standard format, So one stick and pull it past the data. So the products of its products services the one very like the business logic To insert the data, insert off our database, then service basically give response off the newly created product with the controller controller, set it in the appropriate response object on basically send it to decline. Right now, Derek, couple of things that we can improve here, such as we can have a constant for this hard coded message on. We can even have a default response object defined so that we don't have to write state as equal to 400 in each and every controller. Right now, let's suppose that in this controller file we have been controller site. So in the case book, you will have to write this thing again and again. OK? So instead, what we can do is we can basically create or the four response in a constant. So let's just create two things in the constant. The Force one is to create the message, and the 2nd 1 is for the default response. So what I'm gonna do is I'm going to create a full over here called us Constants. Okay. On inside of this, I'm going to create a file called us in next door, Jess. Okay. And here I am going to simply say model export equals an object. Okay, so the first thing that I want to export is there Default Serwer response. Okay, this is going to be an object. And inside of his object, I'm going to say status as 400. Okay, message as an empty string is off. Now and then I can simply say body as an empty object on. I'm going to make it off this defaults of a responsible here. Okay, So in sort of defining it as an empty object over here, I'm going to first of all, grab it from the constant, so I can simply say const constants according to require constants. Okay, on we don't have the space where the index dot Js Well, because if you simply specifically for that, then beautiful it is going to look for their two things. The 1st 1 is toe. Look for the name of the file. Exactly Like the name of the folder, if not found that it will pick up the index, it or just okay. And now what I want to do is I want to basically a sign this before response. So this object, okay, so I don't want to mess around over this thing. So what I'll do is I'll create a copy off this object on a sign it over here. Okay, So I'm going to make use of the spread operator and here against implicit constants dot the force. Our response. Okay, so now I don't have to set for 100 explicitly over here, and I don't have to set the empty body over here as well. Ok, so as you can see these two lines are the more So let me see if this Now, let's check once again. So, for example, if I change the product toe Puma and the name of the product Oh, for example, sports shoes. Okay, Now, if I click on this again, we should see the same thing as against the same thing that busy over here. And if you go to did aboard Creedy on simply click control are the nez agency. It is going to refresh the view on going to show you the new records. All right, So, as you can see, we have basically reduced the number of lines that we have to right here by defining our default response. And one more thing that we wanted to do is tow create a constant for this message. Okay, so what I'm going to do is I'm going to create another constant over here. So here I am going to simply say product message, okay? And this is going to be an object for the key. I'll say product on the score created. Okay. On for the message. I'm going to simply corporate from here. Okay, on. Let me be a street over here. All right, So here's what I lose earlier demonstrates from the constraints. So here, Elsa Constants. Dark product message. Dark product created. Okay, so we have basically okay, the constant for the same. So let's stairs this now. So I'll go to the postman on here. I'm going to simply create another product called a Sport Shoes New on the Enterprise toe. $200. Click on sand the residency again. We got the same response. All right, so there is That's it for creating the route controller as a less the service for the create product functionality by creating the post product A pia. So I hope you were able to follow along on. Thank you so much for watching this video. 14. Mongoose toObject Transform: Hello, everyone. So as off. Now, when you will recreate our product, then this is the information that is being returned. Okay, so we get the ideas on the school ready, and we also get this another extra feel Cordless double windows, Corvi, which is actually not required on the front and right, and it deliberate. Or if we return the I d. Key over here in a straight off under school. Ready. So that will be better for different Trento trade over the data. Right? So what we want to do is we want to basically transformed this object or the document. Donato have this double underscore of the field as well as the underscore idea Toby presented as I did itself. No, there are various ways in which you can perform this task, such as creating a custom function for manipulating the data or maybe using a projection to remove some of different from the mangoes or what you can do is you can make use off the to object transform that is available on this scheme options so they never equality toe object . My third on a particular document, it will basically put form some manipulation that is defined by you. So if you basically visit the mangoes jay's dot com okay, and go to the dogs and simply search for transform. Okay, so you will see that if you click on this. Okay, so these are the options that you get for the transform function. Okay, So you have access to their document which represents the document that is being converted . Then you have these right object, which basically the present the plane object, which has been converted, and you can pass some extra options. So, for example, in the scheme are you can simply, for example, delete this underscore i d. So whenever you call the to object mattered on a document, this idea will be removed. So as you can see, the heavy man shown the example. So, for example, there is a dog on if they call the to object without the transformation, it hasn't underscore ready. But if they call it with the transformation, okay, then these underscore ideas move because this idea is basically removed from their transform itself. So what we'll do is we'll create our own transform. OK, so we're going to basically store the endoscope Rieti in the idea itself and we're going to basically return it. Okay? And we're also going to remove the Dubliner school. We feel so like this. Do it now. So if I go to the court base than if I goto the models, Okay, so if you go to the data base models product model So here we have another option called us to object. Okay. On this to object is going toe have the transform. Okay. Ondas aside, their transform is going to be a function which has access toe three things there document the right object as well as the options. All right, so here's what we can do is we can manipulate the return data using the right object. Okay, so whenever the to object my thirties card on a particular document weaken basically my new bullet, how things work. Okay, So, first of all, what we want to do is we want to basically get rid off the underscore I d on instead written on the ideas. A key. Okay, So what I'll do is here First of all, get the idea before the living so here and said that not ID equals red dot Underscore Ready ? All right, Then I can simply say delete right dot under school. Ready? Okay. On Finally, I can also deliver the right start. Double underscore. Be okay. And we can simply done this right over here. Okay, So now what will happen is valuable. I simply goto the product service, which is where we are basically returning the data. So instead of directly returning this result, I would like to call the to object method before returning. Okay, So, festival I'll basically get the dessert. Okay on. I'm going to simply written Desert Dart to object. Okay? And remember that this to object matter can only be applied to a single document. Okay, Single document is nothing but our record in sort of the longer to be collection. OK, so this one record is a document. Okay, so if you have the list of documents, then you need to it right over that list and applied to object to individual documents. All right. So currently we are basically inserting or saving. Hence, we only have one document in the result. Okay? So we can simply apply thereto object directly to that result. All right, so now let's scrap this in the postman. First of all, I'll go to the terminal and start this all over again. Onda, let's go to the postman now. So for example, if I named the product as formal shirt I named the brand as pretending Learn on for the price I'd say $80. Okay, now perfectly consent Then we should not have the underscore I different over here Instead , we should have the i d on. We should not see this dollar. No score of a field. Okay, so I just try this now. So as you can see this time we have the i d feel instead off underscore Ready? Okay. And this is just detained in the name off key Norden The value A kid of a losing. And as you can see, we no more have the double underscore v field. Ok, so we don't have to basically like the logic ourselves to remove the UN required field instead of genetically transformed this schema by defining it over here. Okay, on Remember that this to object. My thirties only going to change the data when this method is basically called. Okay, It is not going to affect the data that is inserted inside off the database. So if we have a look it in the robot pretty then, as you can see, we still have the double underscore v Full interview. DWS Okay on. We still have the underscore reid in their database. But it's only when the time off for retrieval or on leaving the time off showing the data to declaim were basically transforming this object so that it is easier for the claimed to read and understand. OK, so, guys, that's it for this video on. I hope you we will do follow along on. Thank you so much for watching this video. 15. Create Product API Schema: Hello, everyone. So in this really, if you're going to create the schema for R a p A. So what do I mean by that? So so far we have created the pay for creating the product. Right now suppose that if the front and try stools and extra feel, for example test right, So we don't want toe basically allow this kind of value Toby inserted inside of the database and neither we want to entertain such values, Right? So in such cases, we basically want to return another and tell the claim that this kind of values not required on even if the user tries to enter any sort off invalid values, for example, if the user twice to basically send the prize in the form of string. Right. So what we have to do is we have to basically add a lot off logic to check what kind off Baylor is saying to us on we can we have to basically validate the type of data, for example, if it is a string or number or an object, or in a day, okay, things like that. So instead, off us having toe right, all the things mentally What we can do is we can make yourself a level really toe validate the objects. Right? So the name of the liberally is called us joy. So let me to show you so if you basically search for joy npm so earlier. This level used to be over here on this package, but currently this is replicated on this packets has been moved to add There it happens less joy. So let me simply search it over here. Okay, So this is the package that we want to install. Okay, so this is the latest one. Andi, what we can do is we can define a schema rate objects scheme. Okay, So, for example, let's consider this example over here. Okay, so they have the user name, password, access token, Berthier, and email. Okay, so they have basically defined the schema, right? So this is an object schema. Now, what they're basically doing is they're basically calling the validate method on the joy liberally, and they're basically passing the object that they want to read it against this scheme out . So if anything fails in accordance to what is defined over here Okay, so this is going to return another. Okay, So basically inside of the desert, they have another key. And if there is no, that means your object is valid on If there's not null, then they basically tell you like what is invalid border? The freedoms those are invalid on along with the message is right. So, for example, if you send the email is a simple string without any dome in. So this is going to generate the error message for you, such as the email is not valued. So this kind of flab really helps a lot. You don't have to perform many techs, OK? All you have to do is defined your object schema on. You have to simply validate against your payload, right, so in articulated will be requested body. So it's in very awesome library. I really love this level. It is one of my favorite library on because it reduces a lot off development time and it basically removes all sort off custom logic that you have to write to attack the request payload. Okay, so what we're going to do is since we have created the for creating products, we're going to define our joy schema for how our request what he should look like. All right, so let's do it now. But first of all, I'm going to install this packet switches at great happy size joy. So let's head over to the court base and open up the terminal. And here I am going to simply saying be installed at that. It happy slash Joy on. Once we have it, we're going to define this schema for the create product AP I Okay, so for that what I lose, I'll basically create our for lead over here. Korda's E B I schema. And in sort of this, I'm going to create a file called us Product schema. Okay, so on Lee product literate schema will go into this particular file. All right, so as you can see, it is installed. So let me clear this out. Okay, so in this well will store all the product related ap a schema. So let me first for import the Joy Library. So I'll say const Joy called to require I bet it happy slash joy OK on I'm going to export a function. So here I am going to simplicity model, got exports, create product schema, okay? And we basically wanted to find the object schema. So I'm going to simply say joy Dark object dot keys. Okay. And insert of the keys, I can pass an object. Right? So here I can define all the feels that I want to elevate. Okay, so first of all, I want to validate the name, so it should be off type joy dot string. OK, so this is how you defined it. Type of the field is by using the joy elaborated itself. Okay, So you can simply a joy heartstring on. If you compulsively warned this field do president in the payload, then you can simply say required. All right. Otherwise it will be ignored. If it if it is not sending it will be fine. OK, But if you warn that frill Toby compulsorily there that make use off the required method Okay, then I can simply surprise as joy door number. All right? And then I can simply say dot required. All right. And the last one is the brand. So here, again and again said joy dot string not required. Quite simple. So we have successfully created this schema on in the next video. We're going to create a middleware for relegating the product. Ap I object Payload with this particular schema. Okay, So what will happen is if you remember the architecture diagram, we're going to basically call them a little. Where from the route itself On. We're not going toe past the request. Do the controller until and unless there's a scheme eyes validated. OK? Because there is no sense toe, pass your request. Put the controller OK then to the service and returned the error from there. Why not simply return the other right from the middle, where there is no need to continue forward if you are not getting what is required in the request Payload. All right, so that's it for creating the joy schema for our create product, FBI. In the next video, we're going to create the middle. Where for validating the request payload with this particular schema. All right, so I hope you were able to follow along. And thank you so much for watching this video 16. API Schema Validation Middleware: Hello, everyone. So in this video we are going to implement the middleware for validating the base schema. So, nipple, it is really basically the finding BBs came over here. Now we basically want toe Adam middleware on the road so that we can basically take this schema before handing over the request to the controller. OK, so first of all, what I'll do is I'll basically create folded over here called as middleware. Okay, on here I'll name the file s joy Schema Validation Norges. Okay, on here. First of all, I'll require the joy packet. So here, Elsa Const Joy equals require. I did it Happy slash Joy. OK, on here. I'm going to simply export a function called this model Nordic port, not validate body. Okay, so this is going to be a function okay on it is going to basically take this schema that we want to validate. Okay? And since this is a middleware that we will be adding pull it out as a sub stacked middleware. So this middleware is going toe have the access, but the request response and the next function. So here I can simply written request response and the next function. All right. And instead of this, we're going to write our logic for evaluating the schema against the request body. Okay, so first of all, what I'll do is I'll basically at this middle. Where did out. So I'll go to the protocol on I'm going to require the joy schema validation. Okay, so this comes from middleware slash. Enjoy schema validation. All right, on Dhere on the rug level, I can simply say joy schema validation got validate body. Okay. And since this validate body middleware basically expects a schema that we want to validate . So we already have this product scheme over here, which is defined, So I'm willing to simply imported over here. So here I am, going to simply seconds. Product schema equals require, and I'm going to get it from eBay. Schema slash product schema already on Dhere in developed body. I'm going to pass this a scheme eyes product, schema, dark, create products, Chemokine. Since this product schema file is going to hold my people schema for various product related ap eyes, I'm simply fetching the cadet products came on because that's what This road, this four. Okay, so that new format disobeyed on going toe. Pull down the product control over here. Right. So this looks good. Now, what we need to do is we need to basically have the logic for validating this schema. Right? So we have everything we have the access to the request response and the next function. We also have this schema. All we need to do is to call the enjoyed Aren't valid method. Okay, So for writing the validation logic, I'm going to create a functional here which we can reuse it later. So here and simply said Const really did object schema on it is going to go function right on. It is going to have access to the object that we want to validate. Let's call it data itself. And it also has access to the schema against which we want to validate this data. All right, so we're going to pass this daytime this schema from this really great body mentor. Okay, so here I am going to simply say validate object schema on for the better. I'll get it from requested body because this is where the device present on. That's what we want to relate it. And in the second argument. I can pass this schema that I get it from here. Okay, so now we're here. We can make use off the joy Very great method and compare both of this object with development method. So here I am going to simply say, const reserve a quarto joy. Not really Did. Late in the fourth argument, you have to basically past the object that we want to. Well, it it on. Then you have to pass this scheme under the onto a little. Okay, on simply, you will get the dessert, all right. As defined over here in the library page itself. Okay, on if this is valid than the other key on the result object will be no. Otherwise, it will have some values, like boards invalid. Okay, So what I'm gonna do is I'm going to simply console log a message over here. So here I can simply say joy schema valuation result late, and I'll simply bring the result over here. So let's just say this now on. Let's try door on the create product. KP I. So, as soon as this particular out this hit, So the first model where that is going toe will be very dead body on it is basically calling. This method of it is validated object schema. And here we are basically validating the object on bringing the result. As of now, we are not calling the next middleware. That means this producer controller will never be called because this village it body middleware, is not calling the next function on as you remember to call the next middle very unit to call the next function. Okay, so I request will be hanging. But that's okay. We just need to first to fall completely logic for validating this came over here against you. Let's does this now. So if I go to the postman And now, for example, if I try to send another field called us best okay on the values Ultra test, then if I tried to hit this now So let's see, what do we get? So it against the under terminal, we have Joyce Kim Operation Desert on in the other. It says validation error on the problem is that the test is not allowed, right. So instead of the product schema, we have only defined three fields right hand Steve. Other fields are not allowed on. In fact, what we can do is we can return the other from this middle there itself for lead. We don't have to oppose it further to the controller Onda, Let's try to test other things. Such as, For example, if I try to send the price in the form of string instead off number, let's see what we get. So instead off, for example 100. If I tried to send this in a string. Now let's try toe test this. So if I hit this and go to the terminal than as you can see currently the door Eskimo Validation Desert is showing Now that means the validation is right. But actually this should not happen, right? Because in the product schema, we have defined the place as a number. Right? So there is another concept called us Khan water. Enjoy. Okay, so what Joy tries to do Is that for example, here we have defined the prices number, right, but we're sending the price in the form of string. OK, so what joy tries to do is it automatically tries to take that if that particular spring Okay, whatever it is, if it can be converted toe a valid type. For example, this 100 is a valid number, right? The only problem is that it is sent. Insert often string right. So what it will do is it will automatically convert this string into the number. So that's what they joined us. And even if you have a look at the terminal, then as you can see here, it has already converted the price into the number. This is not a string, OK, but if you don't want such behaviors that what you can do is instead off, allowing the joy toe convert by itself. You can disable this convert functionality, so the way you can do it is by simply going toe. The joy scheme of elevation and unsettled, developed did matter. You can pass an option called this convert Okay, and you consented to falls by default. This thing is, said it true, but you can set it to falls explicitly. So let me say this. Now let's go to the eternal on Let's go to the Postman again and again. I'll try to hit this and let's see what happens. So if I go to the terminal, then as you can see it say's validation error on it says price must be a number, right? So as you can see this because I've said they can work with the false, it is not converting. Okay, so by default, this option is true. But you can set it to according your needs. So currently I'm going to keep the convert falls as it is. All right, So now what we do is we will try to grab the validation message on Try toe, prepare the error response right from the middle where so, as you can see here is the other object, Onda. We can simply get the other details by accessing this retail property. So let me try doping dusky and let's see what is there in this particular key? All right, so here I am going to simply say dessert dark adit dot details. So let's say this now. Go about their daily mail. As you can see, the Silver City started automatically. Let's go to the postman on dry to hit this ap. I know if I go to the terminal, then as you can see, this is the deal ski on these other things that it is holding. So it is basically telling you like there this is happening. And the message is Well, okay, so what? Kind off, what is happening? So the only thing that we require is the message and depart. Okay, so we'll take out this doting on. We'll send this as a response to the client. So what I'm gonna do is I'm going to prepare an adder object. Okay, so here I am going to simply call it as const. Other details. Okay, so I'm going to simply map it over this particular area, which is retail. Sorry. So I'm going to simply say result. Dar Adal dot details dot map. Okay. On in sort of this map, I'm going to get a value. All right, on what I need to do is I need to grab the message as well as depart. Okay, So what I'm gonna do is I'm going to simply it on an object over here, okay? And this error digital will be a new worry with whatever object that Britain from here. Okay, so insert off this. I can simply say as the blue dot message. Okay, so I'm tryingto access the message key. From here on, I would like to also passed the part over here. Okay, so I can say part as value dot but quite simple. All right, so now, instead, off control logging this whole object, I'm going to simply print the head erotic itself. All right, select new clean dude over here on. Let me bring the other details over here so that we can clearly know what kind off other will be responded back to. Declined. So let me bring this over here a legacy of this. Let's go to the postman on again. Hit this particular thing. So now this makes a lot off sense, right? So it says error as price must be Number on depart. All right, so this looks much cleaner on. We can send this thing to decline, okay. In the response body. So what I'll do is I'll basically apply if check over here. So here. I can simply say, if result dark hair that is present, then simply basically tried to find out the other message, okay? And simply redone the energy dense over here, right? And if the other is not found, then simply didn't know. Okay, so this is what we want to do. So Now what I lose. I'll simply tried to grab this return value over here so I can simply say const Heather equals this. So here also, I can apply enough check, and I can simply say if the other is present, then simply respond to declined with another otherwise simply called the next function. So here also Britton next. All right, so this is going to call the next middleware, which is create product controller, right? So if I go to the broader clouds so if the next function is called from here, it is going to call the create part of controller on, the further things will execute. All right, But if the validation fails than here, we'll get the other and it is not going to be null. And here begin simply this point back to decline. So just like we have prepared the response object over here in the controller. Similarly, we're going to do the same in the middle of it itself. So let me festival grab the constant, so I'll say const constant equals required, and I'm going to grab it from the constant on here. I can simply say like this ponds equals I'm going to spread over the constant dot the force of a response. All right, on all I need to do is to simply say response dark body equals other object itself for the message and simply say response dot message equals invalid fields. Okay, So instead of defining this hard coded message over here, I'm going to define it in the constants. So here, I'm going to simply add another key over here called us the quest validation message on here. I can simply add a message, for example, bad the quest and for the value I'm going to paste that particular spring on. What I'm going to do is I'm going to simply that this constant on I did over here. So here I can simply say constants dot the quest. Validation message dot Bread request. All right. And now I can simply say written response darts status as this ponds north status. Andi, I basically send this whole object from here. All right, so we're basically sending the response right from the middle. Where itself back to declined. No need to oppose it further to the controller. So let me say this now on, As you can see, this always that he started? No, If I tried to go to the postman And if I try to hit this ap and now, then the patient redone in every response, specifying that the price cannot be string. Okay, so let me just try this now. So as you can see, we got this treatise has 400. The message, as in millet fields on the body as an array off objects in certain Off it, it says the address price must be number on depart as well. All right. And if I tried toe, for example at any extra field, for example, if I try to fix this price thing, OK? And now if I tried toe anything over here called us test, okay? And if I try to hear the Abia? Then again it says in Millet field test is not allowed. So as you can see, this is how the joy leverage can help us a lot in, you know, preparing developed Asian messages matching the schema against any object. Andi can help you in preparing the error messages as well. Okay, So you guys, this was all about creating validation. Middleware. So we're basically validating our request body over here on, we have a plate this particular middle. Where? On the create product Out. Okay. So Indian. Unless this validation is success, we will not be able to call the create product controller. Right. So that is that's it for this particular scheme of validation. Middleware on. I hope you were able to follow along on. Thank you so much for watching this video. 17. GET API: List Product with Pagination: Hello, everyone. So, in the spirit of your going to implement the FBI, forgetting all the products so it will be get throat on the product. So basically lays down on the products, right? So so far, we have great Did they pay for creating the product? Now it's timeto create the get all products appear. So what I'm gonna do is I'm going to define that out over here. So here I am with this implicit out dot Get. Okay, So this is the extra to be request type of get hands. I basically called They get mattered. Okay. On did out that I want tohave Is this slash itself after the baby even slash product as different over here. Okay, then here I am going to first of all, trans for this request to the product controller. So let's go to the product controller, OK? And here I'm going to create a method called as Guettel Products. So most of the things is going to remain the same all willing to do it, Scholar, Different service as well as some of the different message someone to simply copies on going toe. Best it over here. Okay, on here I'm going to simply say get all products. Okay, Andi, I'm going to also create a service called us. Get all products, which I'm going to define in a bit on the here instead, off Prada created, I would like to create another constant called this product fetched. Okay, so let me create this. So hit. Also product fetched. Okay. On for the message. L see a product fetched successfully. All right, on going to me use off this particular constant over here. All right, so this looks good on for the console. Look, I'm going to simply copy this and place it over here, okay? Get all products on. Yeah, that's off. The thing looks fine. Okay, so this is their wanted off, you know, following the appropriate architecture. So once you have a very different architecture, you can simply copy the existing court and make Houston this right. So next thing that I want to do is first of all at this particular controller to did out. Okay, so I'll go to the park roads on here. I'm going to simply say product controller dot Get all products. All right. So we have created the controller, and I think it's ready on Insert off this Guettel product. We don't need to pass the request body. Okay, so it's off. No, you're not going toe pass anything later on, we'll pass some of the things because we will also implement the pagination. But as off No, I'll just keep it empty. Okay, on. All I need to do is to create a service. So let's go to the product service, okay? Going to simply copy this ongoing toe pasted over here on instead, off create product. I'll simply call it as get all products. All right on here also, I changed the console log name over here now, many to write the credit for getting all the products. So here I am going to simply say, Oh, wait, Product don't find. And it is going to be an empty object because we don't need to find on indignation. We just want to get all the products on. Let me call it products instead of for product. Okay, Andi, they don't need to save this. Andi has asserted that to object Mutharika and only be applied to a single document. But here we have list of documents, right? So we cannot applies off now. So we'll see later. How can we basically do it? So what I'm gonna do is I'm going to somebody. Dundee Products is off now. All right, so this looks good. All right, on. I think we have the whole floor, Eddie. So, as you can see, we have the route for getting all the products. Then we have defined the controller on. We have the proper messages as well. And then we have the service which actually fetch the product from the database. Right. So this looks good now alleged as this and I already have this award, Ernie. So I'll go to the postman, and I'll simply copy this. You are ill on. Go to the new tab on going to place it over here. Unless does this now. So as you can see, we have all of this product. Okay, so we have this state outscored message as product fetch successfully, and instead of the body, we have a day off objects. Okay, Are the idea of documents. Now it is said that the two object matter cannot be applied to the way off documents hands were getting this underscore idea and the double underscore. Refill again, right? So how can we handle it? Well, the one ways to simply it right over this product on call the tow object method on eat and individual product. But instead of doing it over here, why don't we create a helper method which can be the used across multiple services, So we will not call the to object matter over here. Instead, we will call the hell parameter which is going to transform our document. So here I'm going to create a folder guarded, eyes headed. But And instead of this, I'm going to create a file called us Baby Helper DOrtiz on here. I'm going to simply export a function called less model or export dark. Let's call it does form it longer. Data OK on. This is going to be a function. All right, on. But it is going to receive the data, OK? Or we can say it is going to deceive the document. Okay, now, this can be our day off document or the single document itself. All right, So what I'm gonna do is for stuff all I'm going to simply check if this is an array, so I can simply say, if dot is a re so I can make use off this easily matter which is going to written William Value on, we are going to simply passed the data. So if this is an array of what we need to do is we need to treat over this data and call the to object method on individual document. But if this is no ordinary, then I'm going to simply return data dot to object. Quite simple. Now let's handle this list of items, and here I am going to simply make it off before off loop off these Allah script. So here I'm going to simply say, four value off data. Okay, so in Egypt aeration, I'll get a single document. So here I can simply say value dot to object. Right now, we need to store this newly transform objects somewhere. So I'm going to simply defined a new data list over here. So let me color doesn't new data list equals and empty array. So here I can simply say new data list door push on here inside of the post. I can make use off this value Dato object. All right, so this makes sense and at last word again simply does return this new data list. All right, so we have this helper mattered. Ready? So again, in charge board this help our method is doing it is checking whether the date other descend is an a day off objects or simply an object. If it's another, they need basically treats over there that it on simply called the to object on each and every object in that particularly okay. And if it's sensing a lot object, then it directly cause there to object. Method. Okay, so now we're going to make it off this form it longer that I helped mattered insert off our service. So let me post old require this, so I can simply say const and I'm going to pick up this matter. But let me first to fall require the helper so I can simply go to the helper. Then I go there to be helper, and all I want is the former Mongol methods, like in simplicity for much longer data mattered. Okay, so now, instead, off, you know, a trading over the products over here. I would like to simply call the format bongo data, which will do the task. So here again simply said return for much longer data and I can pass t rt off documents over here, all right? And I can do the same thing in the create products of he says, Well, so instead of calling you to object over here, what I need to do is I can simply make use of the format mongo data on. I would like to simply positive desert over here. All right, So whatever comes from the database, whether it's and single document or the list of documents, it is automatically will be handled by the former Mongo Helper method. Right? So this looks good on what I'll do is I'll go to the Postman on, tried to hit this. Now let's see what happens. So as you can see, our data is transformed now and we no longer have double underscore 80 nor we have the double underscore V fail. All right, let's even try toe test the create product as well. So here I'm going to simply add a new product so that we can see clearly so here and simply say formally, shirt new. And if I try to basically hit this now. All right, so let me try this. So, as you can see again, this is transformed. Right? So here we were calling toe object directly. But now we're basically handling in the hell parameter. Right, So this looks good. So now what I want to do is I want to basically implement the pagination in this particular e p A. So users can basically Pasto will use which are skip and the limit. So escape is going toe, you know, escape the number of records that the user saying on the limit is going to limit the number off record that is written by the FBI. Okay, so that way the front and can implement the pagination. So first of all, we'll try to get this perimeter in the credit programs. Okay, So the way you can pass query programs is by applying discussion mark than, for example, skip equals one. And, for example, if you need to pass another curry powder, and then you can simply say limit equals stand. All right, So this is how you can pass the credit problems. All right, on what we need to do is we need to First of all, create this schema for the credit problems. Right on. We're going to validate this on. We're going toe. Also take, like if any of the perimeters are sent than that won't be allowed. So let's create this schema for the credit problems. So I will simply go to the he pay schema, then product schema on here. I'm going to create a method called as model dot exports dot Get all products schema. All right, on this is going to be joy nor object darkies on inside of this. I basically want two things. 1st 1 is this skip. So here I am, going to someplace Enjoy dark string on the second perimeter I want is the limit. So this is going to be this string as well, Okay. And as off No, I'm not setting the required method because if user doesn't send it, then by default, we will set our own skip Andi limit method. Okay, on which I'll show you in a bit so will not make it compulsion. Toe always parts this keeping the limit value. OK, so now what I'm gonna do is I'm going to make use off this schema and apply this scheme of in addition, middleware on the gate. Productive outs. So let's go to the workload on Dhere. I'm going to simply say so. Here. I'm going to simply say joy schema Validation. On this time, we're not going to call the village it body because actually, we won't. Okay, validate the credit problems nor the body. Okay, so the body is basically validating the requester body. But what we want to religion is the request. Your credit data. Because that's where all these fields are basically President. These are not President insert of the request body. Okay, so whatever you passing the body, that's president in the request body. But here, basically, we're passing the query problems, so those with the president requested quickly. So what I'm gonna do is I'm going to simply companies and create another method called us. Violated 20 bedrooms and instead, off request body. I would like to say the quest Art Kredi has aside that request road query is going to hold this variables that you pass in the query parameters OK, and it is going to hold in the form of objects of for example, skip is going to be one limit is going to pretend on it is going to be insert often object in the form off key and value. All right, forget. So let's make use off this really good credit. But I'm really where Over here now. Instead, off a literate body over here, I can simply make use off the validate curriculums, and I can pause the product schema dot Guettel products schema. OK, quite simple. So you always lets does this now, so I'll go to the postman on First of all, I would like Toa simply pass another key instead off what we have defined in the product schema. Okay, so the only thing that is allowed is this. Keep in the limit. Now let's try some other thing. For example, test on. Let me send this. Now let's see what happens. So as you can see, we got this error message that says Invalid field and say it's test is not allowed Now what we want to do is we want to basically make it off this skip and the limit mattered on applied imagination, right? So let's do it now. So first of all, I'll go to the court case. Then let's go to the get product controller on Dhere. I would like to pass the request door Ready There now we're here. Ok, so this is going to send escape and the limit value so they get all products office. So let's go over here. So here we basically want toe get this keeping the limit value. Right? So here I am going to simply the structure, the value. So I'm going to simply say Skip and they limit OK. And I can also initialize this value if these are not sand. Okay, so this will be there before its value. So far, this cape I want toe have the default value a zero on for the limit. I want to have the before to a US 10. Okay, so let me see it. This now on, let's applied equality for the pagination. So the way you can do it is by simply calling this skip matter. Okay? And pass this skip value on Remember that they escaped Value expects a number, right, But in credit programs, you will always get string normal award. Okay. So for example, in certain politicos body, you can pass different data types that such as the bullion or the number, but in case off the credit programs, there is no way you can specify their type. Okay? It is always going to be string. So what we need to do is to convert this string to the number we can make use of this mentor called s parsing. Okay, so here, I'm going to pass this key value. Then for the limit, I can simply call the limit matter okay? On the monk goes on here also, I can simply say Parsons as, for example, limit value here. Quite simple. So I think our queries ready now on. Let me simplicity of this. Let's go to the postman on tested. So if I try to hit this now, then as you can see, we got dessert. Okay. And for example, if I want to get the 1st 3 product than I can simply say, skip equals 20 on limit equals three. Quite simple. All right, says Agencia have the 1st 3 product. If I want to have the store products and skip this one, I can simply say Skip Nichols, one on limit equals toe. OK, so this time we should have toe products. The 1st 1 is this sport show and 2nd 1 is this sport show new. Okay, so that's does this now, As you can see, we get distributed on. If I don't pass any off the value for this skip and the limit than by default this keep value will be chosen at zero as different. Over here on the Limited will be chosen. Ask 10. So let's go to the postman does this now. So as you can see be arrogating the all the products which are not more than enhance We're getting approximately 5 to 6 product that we have in their database. Okay, if we have more than will only be getting 10 because we have defined this defaulted really ? For the limit over here. Okay, so you guys, that's it for the pagination on. I hope you were able to follow along on. Thank you so much for watching this video 18. GET API: Product by Id: Hello, everyone on in this video you're going toe implement the Abia toe, Get the product by a particular writing. So far, we have read the AP forgetting the list of product. But now nights implement the pair to get a product by the I d. Okay, so I'll go to the court base on here, in the product routes. I'm going to define another out. So here I am going to simply say, daughter, don't get okay. And this time I won't go. Except I d in the form off part perimeter. Okay, so are you. Baby would be something like this. Let me just show you. OK, so do the product. It is going to the same. So, for example, if you want defies this product, then use it is going to pass the i d in the part perimeter. Whatever you pass after the question mark is card as query parameters on this is called this part parameter again. So this is how we basically warned our data. Okay, So the way you can accept the but perimeter is by specifying the colon and I d Okay. And you can name it whatever you want. Ok, I've just named it. I d Okay, so now I'm going to pass this request to the controller, So I'm going to hear define a controller called Esparta controller dot Get product by I D. Okay, so I'm going to define this controller in the controller file. All right, So I'm here in the controller going to copy this on Bay Street over here on going to copy the name. Okay. On Bay Street over here. All right, on. I didn't the console messages. Will onda for the message. It's fine to have the product first. Okay, on for the product service I'm going to call a service called Is get product by i d. And this time I'm going to pass the request dot caroms instead off the request art Pretty. Okay, So your part harems are basically present inside off the request art programs. All right, so there you go. You have your data as well. No. All of you need to do is to create the product service. So let me go to the product service. Let me copy some of the things from here going to modify them on going to create a service called s get product variety and I can be structured the idea itself. So since we have defined the our part perimeter as an I d. So I'll get this idea in the request or problems from the controller. OK, so this office So I can be structured over here so I can hear simply say I d right on Dhere 1st 0 Lord, I would always I loved Dickens whole message over here on going to modify the query. So let me remove everything from here. All right, on what I lose, I'll simply call a method called That's fine by I D. Okay, And I'm going to pass decided. Quite simple on we're going to get the product single product. So I'm going toe college as product itself, going toe past this product to the former moderator on. We can do one more thing, which is toe check if the product is not found. So here I am going to simply say, if the product is no, then I want to run this particular if block so here I can simply say through new and I can posit the message as product or phone. So let's define this message in the constants. All right, so here I am going to simply define our constant Karla's Florida, not phone. And I'll keep the message as product not found. All right, so let's use this constraint. So, first of all, I'm going to require the constant over here. So it's a const constants equal to require constant. On that last, I can simply say constants. Dart brought up message dart product, not phone. All right, Okay. So let's does this in the postman. So I'm going to simply say this on Let's go to the post Mint. No, If I hit this particular ap, I we should get a specific product detail off this product because we have copied the idea of this protocol. Right? So if I heard this then, as you can see, we got the result on we're getting the individual product. Right. So this is what we want on this one. What improvement that we need to do is tow Add a validation on the idea itself. So, for example, if I pass anything dumb, you over here, which is not a 90 so we get another something like cars to object. Ready field for the value. Depart. I D. Okay, so this particular error is basically returned by this particular equity, which is fine by 80. And what it is basically saying is that this idea is not invalid objectivity. Okay, so what Mongoose tries to do is tow Simply convert your string. OK? What? They were I d string that you send a tow, the object i d. And it performs defined operation with the object ideas. So even if you have a look at the data base on if you open any off the product, then as you can see, the underscore idea is an object idea, and it is a special type in the bongos. Okay, so if you send anything to me which is not invalid objectivity, thesis credit is going to return in other. So what we can do is instead of sending this kind off, what we can do is we can basically check for the validation off the 80. Okay, So here I'm going to add developed Asian on the ideas. So first of all, I'll require the mongoose package toe developed Asian so else among goes equal to require Longo's on Dhere. I can simply say if among goes door tapes, dart object. I d the Lord is valued and I can pass the 80. Okay, so this is going to return a Boolean if this is valid idea or not. Okay, So if this is false, then here I can throw another. So I can simply say through new editor and I can pass the error message as invalid. I d. Okay, so insert off hard guarding the message over here, I'm going to define it in the constant, so I'm going to define it in the database message. All right, on here. I can simply say in valued I d Okay on here also, I can simply say invalid. I d. All right, so, going to simply make use off this constant over here. So gonna say constants Dart database message dot invalidating. All right, so let me say this. Now. Let's go to the postman on alert. Strike gold on this now, so no, we have ah, property error message. It says invalid. I d. All right, so this looks much better has compared to the previous error message on what we can do is since we are going toe, make use off this check on various Debbie queries. It is better to move this particular logic. Insert off a helper method because we're going toe essentially repeat the same over and over again. So what I'm gonna do is I'm going to simply copy this, Okay? In fact, cut it from here on. I'm going to go to the baby helper on going to create an export. Another matter on the name of the matter will be check object. Ready. All right. On as a parameter, it is going to receive the i d on going to basically apply the check over here. Okay, So what it is basically doing is to same checking the i d. On. If this is not valid than it will throw the other. Okay, So let Merrick where they constant over here. So I can simply say const constants equal to require, uh, constant. And I also knew demon goes as well. So let me the quality mongo. So it's a constant mangoes equals required mangoes. Okay. No, Again, simply get rid off this mongers. From here on, I think I can fetch this. My 30 p just called us Jack objectivity on going to simply call this over here All right, on going to positive idea over here. Quite simple. So this is going to basically throw the error if the idea is not valued. Okay, so let me say this lights. Does this now on Hit this again. So I think that's sort of what is known or work. OK, so it is saying unexpected talking over here, So let me just take this. Oh, so I need toe for Goto. Apply the aero operator like Missy of this. Now, what did the postman again? Hit this again. So as you can see again, we have the same result. And all we have done is simply moved the logic in sort of the helper matter so that it can be used across multiple services and even it other places very where it is required. So you guys, that's it. 40. Get product by I d a p a on. I hope you were able to follow along on. Thank you so much for watching this video 19. PUT API: Update Product: Hello. Everyone on in this good of your going to implement the update product, Tapia wherein user can update a particular product by I d. So the way user will send data is by first fall sending the product lady in the park perimeter on the product Payload in the request body. OK, and it will be Ah, put a p So what I'll do is I'll create out over here so I can simply say rotor dot Put as I said, it will be a Porta Pia and in the part parameter, we're going toe ask for the product. Ready on in the payload. We're going to ask for the information that the user wants to update. So let's define the schema for the same. So I will basically go to the product schema on Dhere. I'm going to create a function on exported, so the name of the function will be update start up schema on this will be joy nor object darkies. And instead of this, we basically want all of this feel that we have defined over here. Okay? Now the main difference that it will have is that we are not going to make use of the required right, Because it is not necessary. That user will update all the tree information at once. User can basically updated according to its need. Okay, so all of these three fields are optional. And of course, if user tries to send any fourth field, then it will be not allowed because we're going to add this schema validation. So they're to go to the products throughout on here. First of all, I'm going to add a validation. So here I am going to simply say, Joyce kim aggravation dot validate body on. I'm going to simply pass the product. Schemer Dart update product schema. All right. And next we're going toe called the controller. So I'll say Product Controller Dart update product. All right, so we're going to basically create this particular controller, So let's do it now. So I will basically go to the product controller on. First of all, I basically copied this existing controller. OK, on going to name the controller as update product going to update the message over here on dhere weren't willing to do is tow call a service called as update product right now to the update product service. We basically need to pass their two things. The 1st 1 is the product I D. On the 2nd 1 is the request payload. So here we are going to fetch it from the two places. The Force one is the request body, and secondment is the request items. So here, I'm going to simply pass the already as the Chris Norton Bedrooms already. And I paused the update in four. As the quest or body. OK, on this update, info is basically going to hold the object whatever the user sends in the body. All right, so we have the data now on, we'll get this. Retained the update product service. So let's go to the products office. All right. On going to copy existing function from here on going to call this product service as a Brit product on duh. I'll just update the message over here as well. And here I can get the i d. As well as update in four. Okay, so I'm basically restructuring whatever I get from here. All right, So what I want to do now is toe First of all, take the validation off the object. Ready? So I'm calling this function so that will work fine. Next, we want to basically update the products that we need to update the equity. Right. So here I am going to first of all, be moved this and I'm going to make use of a method called us. Find one on update. OK, so the reason I'm going to make it off these find one and update my thirties because it is also going to return you the document that you have just updated. If you make use off another matter which is update one, which is also going to do the same thing. But their defense is that this is not going to return you the document. But we also want to send the document to the client. So I'll make yourself defined one and a Brit and inside of this unit to first of all, find the document that you need to update. So here l serves their document by i d So Heroles underscore idea Quito Heidi. Then I want to basically pass the data that I want to update. OK, so I'll just get it from operating for Andi. It is another option that you can pass on, so I'm going to pass an option called us New and started to true. Okay, So what this will do is it will basically give me the objective document. If I don't set this option is true. It will give me the document, but it is not going to return me the abraded document. I want the abraded rug document. Right. So you need to pass this option. All right, so I think this looks good on we're going to go. One thing that began up great on the controller, the level is to update the message. So instead, off product fetched. Let's call it product critic. So here, I'm going to create an under constant called US product updated on. I'll basically call it verdict. Updated success fully. All right, so this looks good on going to makers off this particular constant over here, so I can simply say product updated. So you guys, I think we're good to go. So let's does this now. So you go to the postman and what I'm going to do is I'm going to try to update this part of itself. So here in the new type, first of all, I'm going to select the put over here. Okay? And instead of the body, I would like to pass whatever I want to update. OK, so here I am going to simply past the object on, for example, if I want to update the price. All right, so let's see was the existing place so, currently, 100. Now, let me update this to for example, 1 50 All right, so let me hit this. Let's see, what do we get? So it's this product reject successfully. And as you can see, we got their document along with the updated place. Okay, Now, if I hit things particularly baby, Just Leesburg. Abia. So here we should have the price is 1 50 for this particular product. OK, so if I heard this as you can see, the prices operated in the database and we can even take indeed are both pretty. So if you go to a little over three d first of all, the fresh your database and I think the product waas schedule shoe. So let's go over there. I think it was this one. If I view document as you can see, the prices updated. Okay. Any fine teens, for example, name is well, that will also work flying. So let me just go over here. Let me teens in them as casual shoe. When did you let me update this? As you can see, it is operated over here like me. Get the product list. As you can see, the name is operated on like me. One checked in the database. I'm going to the fresh it going toe of your document. As you can see, the name is a breaded. So the guys that's it for the upgrade. Quickie on. I hope you were able to follow along and thank you so much for watching this video. 20. DELETE API: Remove Product by Id: Hello, everyone on in this video, we're going toe claim in the e p a. For deleting the product because there is the one that is remaining for the product. So let's start implementing the same by defending their out. So here I am going to simply say router dot delete. Okay, so the extra TV method is going to be off. Hybrid it. That's why I basically called the late mentor. Then we're going to basically ask for the i D in the park perimeter. Then I'm going to basically call the product controller dot daily product. Right? And let's define this controller so I'll go to the product controller. OK, on, Just go to the bottom on going toe. First of all, copy the existing court. Okay on going toe. Keep the name as Dilip product. Okay, Going to name the service is the lead product is well on going toe. Update the name over here in the console August Well, on going to define a constant called as product diluted. So that's a product diluted. And the message as product billeted successfully already So going to make use off this particular constant over here. I know that's What is the details? Concern. I'm going toe basically passed the request or problems. Okay, so going to simply pass it over here? I said request door problems. That's it. They're selling it to pass. Let's define the service now. So I'll go to this office on going to copy the existing court from here. Okay. Going toe pasted over here on going to name the service as delete product. All right, on. I'm just going to restructure the I d. Nothing else. Then what I need to do is to update decree. So here, I'm going to simply say find by I d on deal it. Okay, so that's the career that I'm going to use on. All I need to do is to pass the 80 so I'll just remove everything from here. All right, on going to simply passed the idea over here. All right, Onda simply going to return whatever the product is being written. All right, surveys. That's it. And I can also update the console log over here as well. Okay, so this looks cool, and I think our is ready. Soldiers globally. Browser on ledge does this now, so I'll just pick any off the product. For example, if I pick are the schedule show 22. Okay, so I just open up the new tab, going to select the delayed matter. Okay on. Let me just speak up the Ural. All right, So now let's try to on this now. So it's this product diluted successfully, and we basically get the product information that has been deleted on If I goto the least a piano. And if I click on this? Okay, then, as you can see, that popular product is gone. Let's even check in the early years. Well, I told the freshness on. As you can see, we don't have that casual show. 22. All right, So you guys, that's it for the Diliberto Abia on. I hope you're able to follow along and get so much for watching this video 21. POST API: User SIgnup: Hello, everyone. So now that we have the AP ready for the product now let's create the A P I for the user. So the four stupid I'm going to create for the user will be sign a P p a or the race story , Pierre. Okay, so I'll start by creating the database model. So here in their database folder than in the models. I'm going to create a new file. Calder's user, Modern DOrtiz. And I'm going to copy the existing court so that we don't have to write everything again and again. Okay. On Dhere, I'm going toe first to fall named immortalize user. Okay, then. Well defined the user schema. Okay, so here I replaced the name is user schema. Now, the fields that we need are the email and the password on both will be off type string OK on. You keep their times time, true as it is, and I'll also keep their to object. Transform as it is, I'll add another field in their transform, which is toe remove the password. Because, of course, we don't want to send the passport back to decline, So there is no need toe included in the response. So going to simply settle it, right? Dart password. Okay, so now we have the user scheme already. Let's create the route for the user. So I'll go to this our gorgeous. And here I'm going to define the part on the app level middleware. So he writes a slash b a slash re one slash user. Now let's create the route. So here, I'm going to create a new file called as user roads. Gorgeous. Okay. And instead of dissembling recently, first of all, get the express okay. Going to define the rotary as well. So here ends express dark older on. I'm going to simply export this, but I'll get over here. Okay? So if you're going to make use of this rotor middleware over here, So here I passed the route. So he also required dot slash dogs slash user roads. Okay. You know, instead of the user out, I'm going to defend the force route for the sign up. So here l said outer door post. Okay, because the stupid method will be off the post and then point that I want to name will be signed up. OK, now we need toe past this request to the controller. Right. So let's create the controller. So in the controller folder, going to create a new file called as user controller Door chest. Okay. On going to copy the existing controller court so that we don't have to write the things again and again. So I'm going to simply copy this one ongoing Tau Bay Street over here. And the first thing that I will go over here is to require the constant. So here I am going to simply say, const constants equal to require constants. All right, Next I loved it. The controller name, and I'll call you that. Sign up, and we're also going to call the sign up matter on the user service and as off Now, we don't have the users office. So here in this office for that, I'm going to create a file called as User Service door, Jess. Okay. And it's off now. Going to export a function called eyes sign up one night. So going to include this user service in the user controller so that the user service on going to get it from service slash users office on here. I can simply make use of the user service. All right, on going toe. Replace the name here in the console log. Okay, Now, we also want to have the message. So in the constant, I'm going to define the user message, okay? And since it's, ah, sign a bba, I'm going to have a message card as sign up success on for the message and simply say, signed up success going to make use off this message over here. So here I am going to simply say, user message door to sign up success. Now, since we have the control already, I'll basically include this controller in the user out. So let's go to the use that out. So here I am going to first of all, require the user controller on going to get it from controller slash user controller. All right, And here going to simply say, user controller, not sign up. Not before proceeding for that. I would like to add the joy scheme of in addition over here. So we're going toe validate the request body off this Sign up, Abia. Okay, so here in the bay schema, I'm going to find out new ski Michael as user schema. Norges. Okay, first of all, required the joy over here. So this comes from my direct happy slash joy on going to export a function we hear gold eyes sign up on set it to joy dark object darkies And instead of this, I'm going to define the fields that we need. So the force one that we need is the email. This will be off joy off type string dot required because we'll need this. And the next thing I want tohave is the password. So here I am going to simply say password. All right, so we have this scheme already and let's include the joy ski mammal addition middleware. So here I'll say Joy schema. Validation. I'm going to require it from middleware slash joy schema Validation Next going toward this middleware over here. So here I am going toes and police say joy scheme of tradition door to validate body on going toe past the sign up scheme. Also let me first of all, get this schema. So he Elsa const user schema equals total quiet ap s scheme us slash user schema on going to simply make it off the user schema dot Sign up. So this looks good. Let's go to the user controller. So I think the controller is it ready? All of you need to do is to create the service. Okay, on. Remember that to the side of service. We are basically passing the request body on instead of the request body will get the 1,000,000 the password. So I'll go to the U. S. Service and I'm going tobe a structure, the email and the password over here. All right, so now here I am going to upgrade some of the existing court so that we don't have to write things again and again. So going to copy this over here on going to paste it away. A light on going up there, Deacon. So long over here. All right, on going to remove everything from here. Okay, So I require a couple of things such as the user model, so in seconds to user equal to require going to go to the database slash models slash user model. Okay. Going to also require the constant late on day. Yeah, we can work with it now, So the first thing that we need to do is to check the existing user inside off the database , right? If the user with that particularly male already exists, then we need to restrict the user to sign up. So here and simply seconds user calls of it, user dot Find one. Okay, so I'm going to make use of this mother, find one, and instead of this, we can defend the condition. So the condition that I want to pass is email on Devalue will be email or get that we get from the restructuring. Okay. And here, I'm going to make it off the Essex shortcuts. So if your key and the value are same, then you can simply defined it like this, right? No need to pass it both the things on Dhere for stolen check. If the user exist. All right, then I will vote for the other. So he runs a true new I don't on going to define, and Adam s it in the constant. So here in the use our message, I can simply say duplicate. He made okay on the message that I want to send will be user already exist that given email . Okay, on going to make it off this message over here. So I'm gonna say constants. Start using a message. Duplicate email right now. If the user does not found, then we can post it for that. We designed them. OK, Now, before starting the user information directly in the database, What I would like to do is I would like to have the password, right. It is not a good idea to store the password as it is. So we will make use off a library called as Big crypt, which is going to have the password. So, like in festival, install this library, so need terminal. I can simply say npm install be crypt. Okay, so this is the packets that we want to install. So now, as soon as it is done installing, I'm going to basically require the package on going to use it over here. So let me close their Dominion. So here I am going to simply say const decrypt equals two required the crypt. Okay, so now I'm going to make us off this library and here and simply said the crypt. Dark hash. Okay, so this is the method that we want to use on. It basically returns a promise so we can apply the await keyword over here. Okay, on the first argument that we want to past is the plain text passwords. So I'm going to pass the password over here. Next. We want to pass this old around, which can be string or the number, so it depends on the approach that you use. So if you go with the first approach, that is to pass this string than you need to generate this whole string using the big reply already or if what you can do is you can basically let the big rip lovely to generate this old for you. So you for that, you need to basically positive number. The higher the number you choose more complex, it becomes to process the hash. So I'm going to make it off the 12 over here on you can make it off somewhere between 10 to 12. And this will give me the hash password, which also has disordered inside off it. Okay, so what I'll do is I'll just replace the existing password, which is a plain text with the hash password. And now we can proceed with saving the user So he rides a const new user cools new user model on going to pass the 1,000,000 the password. All right, Hopefully this makes sense. And remember that this is equivalent to this on. Same for the password. Okay, All I'm doing is making use off the Essex shortcut. Okay, so now what? I lose, I'll simply call this a matter. So it's a let reserves equal to of it. New user, North Sea. All right, on going to makers of the former moderator. So But first of all, let me require that fight. So it's a constant on going toe, the structure that particular matter. But first of all, let me require from the helper on the baby helper. OK, so going to get the former monger data maternally here going to make it off this method are the result. Okay, so here and say Britain, former monger data and there isn't it. Okay, so I hope that makes sense on I think that the baby is very Toby test now. So let's go to depose mint on who for years Always running. I think it's not. So let me simply start this at what? And now I'll go to the postman on. I'm going to make it off the post. Tapia. The endpoint is slash depends less even slash user slash Sign up. Okay on in the body. I'm going to pass the later Okay, the hero. First of all, define the email as John one at gmail dot com Going to act the password as 123456 So he writes English. 123456 Alleged tried to add extra filtered off what we have defined in the Abia schema. All right, Andi should not be allowed by the middle where? So let's does this now. So I think there is some matter, so that's taking their terminal. So it says of it is only valid. Anything function. So here I am going to simply say you think All right, see if this now we're believe postman had this again, so it against it says invalid feels that means armored. Always working fine. No, I'll basically remove this friend over here on going to simply sign up so large that on this now residency we get the message is signed up success and we also get the email off the user and we're not getting the password because we have basically removed this insert off the user model is against. We have basically multi password. And let's also check whether the user password is stored in the form off hash. So I'll go to little both pretty on going toe click on the user collection. And as you can see, here is the record for the user. So here I am going to simply do this document on, as you can see, the power authorities a store in the form of hash. Okay on. I also like to test another use case. We're user Christ to sign up with the same email, so we should get the error message for the same. So let's test it now. Okay, But the same email. So as you can see, we got the message is use that already exist with the given email. All right, So you always there for this enemy p A. And I hope you were able to follow along on. Thank you so much for watching this video 22. POST API: User Login and JsonWebToken ( JWT ): Hello, everyone on in this video, we are going to create the AP for the logging. So as soon as the user Logan, we will written the decent Web broken or JWT. Okay, so let's start implementing the same. So I'm going to create a post route for the logging. So healthcare ordered outpost, then point is going to be logging. Okay. Next, I want to basically create the validation middleware for the logging Appear. So here. Elsa Joyce Kim amelioration dart validate body. And we're going to pass this schema for the Logan salsa user schema. Dark logging, which we have to define yet. Okay, so let's created now. So going to simply copy this one because it is going to the same. All right, on going to just update the name over here. Right? So this is logging schema because will require board difference in Berlin. The password for the logging as well. Okay, next, I'll create the controller for it. So here I am going to simply rd controller. So here. I'm gonna say user controller dot Logging. Okay, so let's create the controller for the same. Going to copy this one way street over here on update the name as logging going toe update the consular here as well. And also going to create a log in service instead of the usual service. Innovate. Okay, But before that, I would like to update the messages will. So I create another message here called as logging success. All right? And he didn't say log in success. Poor. Let's win one for the So I think our controller is ready. All of you need to do is to create this office, so I'll go to the sign up service on Dhere. I'm going to simply copy the existing one going toe pasted over here. All right, Onda, I'm going to simply name it as Logan is off now going to operate. The consular here is well on going toe. Therefore the logging instead of sign off. All right, so instead of the log in service, we're going to first of all, find the user. Okay, on the fuse. That is not phone. We want to return a message such as used are not found. So what I do is I loved it. The condition over here. So if they're use that is not found, that I want to basically return a message. So I redefined the message over here on Dhere. I'd say user, not phone on here. I'm going to simply say use it, not phone. All right, now, I will basically that for this message over here. All right, Now, first of all, let me remove the existing court from here. Now, here we want to basically checked the password. But remember that here, the user will send the password is a plain text. But instead of the db, we have the hash password, right? So how do we compare them? So there is a method given by the big trip library called us compare. So we're going to make use off it. So here, I'm going to some predict later available called us Israeli. Okay, Andi, I'm going to simply make it off the compare method. So also be crypt don't compare. And in the force argument, I'm going to simply pass the plain text passwords there, descend by the user. And in the second argument, I'm going to be slip as the hash password so we can get it from user password. All right, On, since this basically done, sir, promise I can make use off the of it. Keep all the way here. Okay? Now we can check if the password is invalid. OK, so I'm going to apply the North Condition we're here. Okay, So if this is not valued, then we won't go through the error. So I'll say he had through new editor on going to pass the message. So let me. First of all, did you find the message over here and here. I can simply say invalid bus work, But the message, I'd say Incorrect buzzword going to makers off this variable over here. Constants dart. Use that. A message. Dark invalidpassword, right? A knife. The password is value. Then it's finally time to basically create the token. So far, creating the token. I'm going to make yourself a celebrity called Jason Ripped Open, and you can find the information regarding the same on the and being paid. So if you're sorts for and Justin Webb broken, then as you can see here is the page for the same. Okay, Onda, uh, all you have to do is migas off the sign method. Okay, so let me just show you. So as you can see, here is the example. So all you have to do is simply Megazord assignment Lead with the jwt dot sign. Then you can pass the payload than your key secret key on. At last, you can pass the various options. Okay, So one off, which is the experts in? Okay, so let me show you which we're going to use, So here it is. Okay, So experience basically takes third time by visiting token will expire. So, for example, you can specify in multiple ways, so you can specify it, like, two days, 10 hours, seven days. And if you don't specify this string, you just specific the numeric value. Then it will be treated as second. Okay, on. If you specify this string without the days are ours value, then it will be treated as a millisecond. Okay, so you can read about this. Like how? The time books for the experience. That too. Good. Okay, So this is how you can pass the expiry date on their videos of their option that you can pass, such as they'll go to Tom, where the Ford one is at just 256 All right. Okay, so let's install this celebrity and implement their token. So I'll go to the corner base, open Andre terminal on here, going to so simply and then install Jason Webb looking. All right, So the packages installed now will basically required this packet. So here, I'm going to someday seconds derogative equals require Jason Webb broken. All right. On at the bottom. I'm going to simply make it off the sign method. So here and said const broken equals the inability dot sign. OK? And as we saw before that the fourth argument it takes is the payload on the payload is also known, exclaims inside of digits and Republican okay on remember that that you should not pass any sort off sensitive data instead of the payload. Right, Because you can basically discord the token without the secret key as well, which we're going to see and it is completely visible. Okay, so you should only put the basic information that you need from the token in sort of the payload. And if you put a really heavy object in sort of the paler than your concerns become quite large and it will then basically create the problem whenever you try to make the request, so make sure you don't put a lot of things over here in the payload on Lee. The things that is necessary for you to get and of course does should not be a sensitive data. So here, I'm going to just put the use ready. So here I'll simply say I d as user dot underscore i d. Right. Next you want to pass is the secret key. So we will try to fetch it from the environment variable. So he runs the process, not envy dot Cigarette key. Okay. And if the cigarette is not found in the woman? Very well, then I'm going to use their before it one. So let's name it my secret key. Okay? You can name it, whatever you want. All right? And let's also defined the cigarette gain the environment variable. So going to copy this going to go to their Dorian refiled going toe pays the security over here on going to name it as for example, a p a. At the red. 123 Okay, on at last. As I told you that you can pass the various options one off, which is the expires in and also showed you the format in which you can pass the time. So he really positive one day as an expiry for this particular token. Alright, so are our token is ready. Now, all we need to do is to simply it under token. So here and say Britain broken. All right on. Remember that I'm using any Essex shortcut over here. So this is a girl and do this all right? What? It is ready now. Alerts Desperate now. So I had ordered the post Mint on going to make it off the end point called us logging on. First thing that I want to test is the request middleware. So that's passed some extra stuff over here. Okay, Which is not defined in the logging ap a schema. Okay, let's see what happens. So, as you can see, it says invalid feels so that's what's expected. Now will basically test another case where the email doesn't even exist in the system on user tries to lovin with their email. Okay, let's see what happens. So as you can see it says user not phone on the next I want to test is the wrong password. So if I put any wrong password over here. Let's see what happens so that you can see it says Incorrect password. Right? So that looks good as well. Now it last. What we can do is we can finally try toe here the AP with the correct email and the correct password. Okay, so let's hit this now. So as you can see, we got the token on for them. I said, It's a sign of success. I think we forgot about our friends. The Logan success, my such. So let's go to the gold ways and I'll go to the user controller. And here I am going to send busy logging success. All right, let me save this. Now let's go to the postman and hit this again. Residency. It says Logan success on here is the deal wt dugan and is there to do that? You can basically the court do token without the secret key. Okay, so let me show you. So if you go to the jwt dot io All right? And if you based your broken over here so that made a show you in a bit? Well, actually, if I may start over here, then as you can see you can see the I d off the user that we added by designing right on the payload. So residency to record the token, you don't require the secret key. The security is only required at the time off verifying their token. Okay, not according the broken. So as you can see, the payload is completely visible along with the headers. Okay. And if you're wondering that if the payload is completely visible, we don't even having the secret key by decoding the token, then how is the data secure internally, Jason Republican. Well, let me tell you that the purpose of digits and ripped open is north to secure the date on that this president inside off it instead, the purpose of the Jason wept Okun is to authenticate the swords or declined from where the request is coming. OK, All right. So that's it for the Logan FBI on in the upcoming videos were going toe basically secured the product a p i, with the help of this Jason Webb broken, that means only the logged in user will be able to access those a p a. Okay, so you always that shit for this video. And I hope you are able to follow along. And thank you so much for watching this video 23. Token Validation Middleware and Protect Product Routes with JWT: Hello, everyone. So now that we have there, took on ready for the user. What we can do is that we can start protecting the products AP. Okay, So what we'll do is we will create a validation, middleware or token validation Riddle where which is going to take this token on going to very dated. And if the delegation is success than it is going toe, move the request to the controller. Otherwise it is going to throw the Arab. Okay, so this way we're going to protect all the product related droughts and his father standing it open is concerned the wave will send. This token is by Let me show you by example. So let's say we have this token, so we're going to send it instead of the request header. So if I, for example, go to the get brooks a p a. And if I go to the headers, then here I can add a harder called assault creation on. I'll basically add the beer over here on going to pace there talking. Okay, so this is how you can basically send it on. This is the recommended way off sending their token in sort of the headers by adding it to the alteration key and in the value citing it as beer, space and Erdogan. Okay, so now let's start implementing the middle where? So I'll go to the court base on going to go to the middle where folder going to create a new file over here on, I'll call it as no configuration nor chase. So here I'm going to export a function called as invalid. It took in okay on, since this is going to be a middle where it will have access to the request, object, response, object and the next function. All right, so instead of this, we need to start implementing the validation. So first of all, I'll get the are the force of a response from the constant. So here l said const constant equals required on get it from constraints. All right. And here, going to define the response object. And I'll make use off this spread operator on here. Elsa, constant dot before it's over. Response. All right. Next word I lose. I'll basically check if the operation is present in sort of the headers. Okay. And since we're passing the operation in detective for this president. So he rented if request dark headers, door authorization. Okay. And if this is not present. So I learned in our conditional here, then what we need to do is a venuto basically toward the error by saying that broken is missing. And if you're wondering why the alteration is in a small letter whereas we're sending the alteration in the caps over here. Okay, so they're forced lately is the cap. So this is already is available in the requester headers, and I'll even try to print it so that you can see properly. So here I learned the console log for the questioners. All right, so here, first of all, what I like to do is to throw the other so gonna say through new edit on going to pass the message is talking missing. So let me to find this in the constant. So here in the request, medicine is it's going to add a message. Korda's look on missing. Okay, so here, against a token missing from headed. All right. Going to may use off this particular constant over here. The quest validation message dot Broken, missing. All right, now, since we're basically throwing together. So I learned it like it's a block over here. So he does do try block than the catch block. All right. And in sort of the catch block I learned dickensa. Log off later. All right. Next, I'm going to move this court instead of their tribe. Look, all right, So it's if know what I would like to do is to simply print or the headers over here so that you can see properly on going to makers off this particular middleware insert off particular rope so that we can see what's happening is off now. So I will go to the product out and here I'm going. Do I did in sort of the Guettel productive talks. So here l said const Broken validation equals require on going to get it from the middle where slash broken valuation. All right. And in this Guettel doubt I'm going to add this model. Where so gonna say broken validation dot Validate. That's it. Okay, so now anybody we hit this FBI are the middleweight is going to run, which is talking amelioration. Okay, on, Let's go to the postman. Okay, so I'm going to hit this load so although nothing is going to return because the quest will be hanging in Sort off the middle there because we are not returning anything. Okay, but we'll see the console log. Okay, so let me cancel this request. Go to the terminal, then. As you can see, this is our request or headers. And as I told you, that the alteration keys available in the small letters Okay, on, as you can see here, we have better space there. Don't look. So now how can we forget the broken from this particular string? So what we'll do is we'll call it this bright matter on this a string and we will take out the token from this string. OK, so let's go to the court base. And here I am going to simply console log request or headers. Dark authorization dot Split. Okay. And here in this pregnant her. I'm going to positive beer. A string. Okay, so let's see. What do we get now? So I look in hit this request and I'll concede Lilliquist on. Let's see what we get on the console. So, as you can see now, we have the ari off two strings. The force one is the empty string. And 2nd 1 is the slogan itself. Okay, so now what we can do is we congratulate Open from the force to index and weaken Dream so their device place from the start and the end is removed Although there is nothing on the end But there is white space on this start. So here began simply say first index dot dream All right, so let me say this again. Go to the postman, Hit this again and let's see, where do we get? Okay, so I'll go to the terminal and it says dream. Okay, so I misspelled it with a string. All right, so let me say this again. Okay, Let's check in the console. So, as you can see, we have their token. Okay, so now we can take this token on very fired using the JWT library. So first of all, I'm going to import the library so here and sickens JWT calls required on get it from Jason Ripped open. All right. And now I can simply say jwt doored very fight. And in the force argument, you have the positive token so we can simply grab it. Insert off a variable, so he runs a const. Broken equals this. Okay, so I posit going over here next when it took pause disa correctly. So I'll get it from process toward envy. Dark, secret key. All right. And if the secret is not found in the environment variable, then we're going to use the same before it spread key that we used while sending the token . So I'll go to the users office on going to grab this default secret key. Okay, Ongoing Tau Bay Street over here. All right, so that may be street over here. Okay, on if the very eviction is successful than the very fine matter is going toe redundant, decoded took on, so I'll grab it in sort of this variable. All right, on going to simply console. Log this over here. So goodness are recorded. Okay? No, I will remove this consulate from here on. What we can do is we can prepare the response so it last I'm going to simply say, return response dart status as response dart students on going to simply send the response object. All right. On beacon, do a couple of things over here in the catch block so here I can simply say response. Dark message equals other dot message on response darts. Status equals 41 Okay, so we're not going to send the 400 instead, we're going to send before one, because that's in standard. I stated Bistrita scored for unauthorized access. Okay. And if everything is fine, we can call the next model. Where? From here. Right. So this looks good. And I would like to also fix their typo there. This president over here. So for the constant basically mean spirited. Okay, so going to operate this over here on here as well? Okay, so let's save this on. Go to the postman. So, first of all, I'm going to remove everything from here going. Don't hear this. So, as you can see, it sees talking missing from the header 95 saying they incorrect token. Okay, send this now. So as you can see, it says invalid token on. If I tried to send the correct token, then let's see what happens says you can see the product out of fast successfully. And if you go to the console, then as you can see, here is the recorded message. So this is nothing but the payload off their token. And you can't even get the payload without even having the secret key. You can simply record it. Okay, Onda, here is the payload that you have inserted a token on. What we can do is now. Since you have the validation ready, we can apply the same validation toe all the programs. Okay, so I'll simply copy this ongoing toe based on all product jokes. I think so. Now all of the particles FBI will be secured. All right, So let me see if this now, let's go to the postman. No, For example, if I try toe hit the which is create product, let's see what happens. Says the concert's stroking missing from the harder. And even if I go to the update ap, I like this. OK, so as you can see, the broken validation is working fine on all of our product. A p i R now secured. Okay. And let's see one tribe with a new user. So, for example, if I basically try dude on the Sina bp with a new user Okay, so here I run this sign up. Okay? On inside of the body I'm going to say Jordan to at the red gmail dot com. All right, let's see what happens. So as you can see the sign of the success going to simply log in now, Okay, we have they're doing over here. Okay. On going to go to the for example product list out on going to pastry, talking over here. All right, let's does this. So, as you can see, it is working completely fine. So that is that's it for this particular video on. We have successfully secured the all the percolated MPs by implementing the validate token middleware. Okay, so I hope you were able to follow along. And thank you so much for watching this video. 24. Swagger API Documentation: Hello. Everyone on in this video of you're going to write the pair documentation. Okay, so it is very important to have all of your ap documented because let's suppose the new developer comes in on. He wants to have a look at all the endpoints or all the routes on what kindof payload is expected. What kindof perimeter is expected and what kind of response is written by the AP, Also the information. Then instead of having a developer to, you know, jump around the cord, what he can do is simply go to their documentation and clearly see every information about the over there. Okay, so for writing, the people were going to make yourself a tool called as swagger. So let me show you. So if you visit swagger dot io Okay, So this is the tool we're going to use on. It is one of the most popular tool for building the AP documentation. Okay, so let me show you what it looks like to have these Gregory pair documentation. So if you visit a deterred or sugar dot io, here is the example Sugar documentation on here is the example. You Why that you get OK, and you don't have to build this. You all of this, you wise build by this work elaborated itself on you just have good idea documentation. Okay, Now you can be spread. I did recommendation in the form off Yemen. Lordy, Jason, I before do writer using animal because it is more human readable as well. It's easier toe update and manage OK on the right. Inside, you can basically see the white that it and birds based on the documentation You right over here. Okay, So first you have the higher level information where you have a basic information about the you either title description and the basic model on what is this scheme used by the A. P. A success for that? It works on a strict aviation GPS or both. Okay, then you have your roads information on all off your roads are bundle inside of a particular model. Right? So all the user letter e pays goes over here story literally. Piers goes over here, and the Petra later DPS goes over here. Okay? And then you have this clearly presentation off what kind of deputies but that it is supposed for the late get Okay, So you have this property. Why on you can not only see the request body like what is required, but instead you contest it out. Okay, so if you click on, try it out. You can actually hit the right, and you will get the response back where there was written, by the way. Okay, so it is a great tool on you should definitely include this in your a p eyes. Right on. At last. You have this mortals. So your model specify all the feels that it can have along with the type. Okay, on you can also live. Where did your document? Over here. So, for example, if I change anything from here, it is going to basically give me the problem at a message. Like where it is happening On what? Land number on what kind of father? Okay, so you can basically test audio document by going over here on the only editor, editor or trigger dot io on bill your document over here. So what we'll do is we'll make use of a library card as so I got express ey. So let me to show you so if you basically service for swagger. Expressive. Why? Okay, on Here it is. Here is the end. Been pickets for the same. So this, like, really basically allows you toe basically have this. You Why that you see, on the right hand side. Okay, on this level, basically expect this worker dodges and file. But as I told you that we are going to write the documentation in Yemen. So what we'll do is we'll use a pack. It's called a C M. Lt's which is going to dynamically convert our Yemen file into the Jason. Okay, on this whether you were not set up, my third requires decision. Okay, so we're going to pass this, Jason are toe the start up mentored using the Amador Lord method, which is going toe dynamically convert the Yemen coaches on a light. So let's go to the court based on Let me open up a terminal. So here ends in pain stall. Very good. You way express. Then the second back is that we need is, um alleges. So is it conceivable? Depicted us are installed. So the first thing that I will do is tow First of all, creative file over here called less so I got out animal late now. What I'll do is I'll go to this. Our door, Jess. So first of all, I'll get this whether you're a packet. So Elsa Const. So I got you a equals required. So you express. Then I need the mlg says Well, so here I will require the, um alleges. Okay. And now we can simply say const Swagger document equals Yemen. Thought Lord on going to pass the swagger door Deimel file. All right, So what we'll do is we really basically define a rope on which we will host disorder documentation, select modify, not out over here. So that first of all, put the comment as e p. A. Documentation late on here, going toe acted out on the uplevel middleware. So here I will say FBI. Hi, friend. Dogs on next. Going to pass this record, you weigh darts are middle bed. Okay. Next, I'm going to posit issue a very way Dark Lord method. Right on inside of this, I'm going to pause the swagger. Documentation. All right. That was this important. All here on Dhere. We can do one more thing, which is to show this documentation on Lee when the environment is not production because you will mainly need this documentation during the development time. Or maybe at this stating. Okay, So going to add a check over here, So here also if process nor the envy not Nord envy Nord equals production then only short this document. Okay, so going to move this over here? All right Now there is only one thing a meaning which is to have the documentation in the Yemen. So I already have prepared the Yemeni documentation because it will take a lot of time to write the recommendation. So simply going to paste it over here there is nothing much complex about it. It's simple. Yemen file. Okay, I just walk you through it. But let me, first of all, show you the U. S. So if I save this, go to the browser. And if I go to the local host 3002 on which are so what is running, then slash e b a hyphen dogs. Then you will see the documentation So it's off. Know anything else? I was not started. So let me start this up again. Okay? On allergic or to the browser again on the fresh air. So I think there is something I don't like to check on. Their terminal sorts is struggle. Your lord is not function. So I think it was set up not Lord. Okay, so let me just fix this up. Let's go to the browser again. Fresher. Okay, so as you can see, here is the appeared recommendation on what we have basically done is we have added the title over here, which is Northern Stupid documentation on. Then we have basically set up the basic model which is local host calling 3002 slash based life even Okay, on this information comes from here. Let's allow me to show you. So as you can see here we have the host and here we have the bass part on Here is their description and everything. Look, a description title. All right on for the schemes as off. No, we are running it on the extractive only. All right, then. You basically defend the part on then you here basically defended out. Okay. And the way you can club all the routes in one location such as all the user routes are over here in the user model on all the products roads are over here in the product model. So the way you can do it is by using tags. Okay, so every road I specify, I also specify the attack over here. OK, so as you can see, the user has retake off user model. Then again, we have this user model over here. Then as soon as we get to the broader globe, then we have the product model type. Okay, so this is how the roads are wrapped inside off one model. Okay? And then you have the modern defined. So what are the fields that user can have and what other feel attacked Burke can have and the AP response itself. Okay, on here. We also have the authentication feature on the documentation itself. Okay, so since all our product a p a r secured using the JWT, so use any to first get the broken on. I did over here in the trays. So basically access all this predicted 80 days. Okay, so let's see, how can you basically test the using the document itself? So for example, I'll try, But on this particular and point which is slash users slash logging So you can click on this straight out. I'm going to enter the palace. John one at gmail dot com Going to enter the password as 123456 Okay, on. Now if I execute this So here I get response and I get the Logan success message. So going to simply copies Let me just 1st 1 show you if I try to hear the product God, FBI, without even the token, it should, you know, not done the response. So, as you can see, it's is talking missing from the header. Right? So now why? Like the broken toe Xs disappear. So I'll go to the authorize over here, going toe, say the better and going to paste Erdogan and click on authorize. Okay, you can close this now. Now let's go to the GATT product. Ap I click on execute. Let's see what happens. So as you can see here, we have all the response that we basically want, Right? So this is how you can missile test all of your a p ace on. If you're wondering, how do you add this or trace feature on the recommendation, then if you have a look at this record rd Emily. Okay, so, first of all, what you need to do is on all your security. You need to act this security information over here on going to specify the beer. Okay, so this basically dinners that you're a basic card. Okay, So as you can see, we have this locks in or here. So this is coming from this thing. All right. Next few school down at the bottom, then you will see this security definition. Okay, so here we have a specified debater, which is off maybe baking name is alteration on. Insert off the harder. Okay, So this is how you basically build the configuration in the amel file for having the ability authentication on the circle documentation. Alright. And at last, we have the definition for the models, such as the user, so use they're gonna have property such as email and the password. It's type and the description. Okay, so it's quite straightforward. There is nothing complex about it. So you guys that treat for the pair documentation on. I hope you were able to follow along on. Thank you so much for watching this video 25. Source code: