NestJS Crash Course - 2021

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody how's it going welcome back to the channel just so recently i got introduced to a great back-end framework for node.js applications known as nest js and i have been loving it so far so what i'm gonna do in this video is basically share my knowledge and teach you how to build a nest js backend application so nest js just so i can kind of introduce it to you it has full typescript support and it's really 99 of the time it's going to be built with typescript which is great and it's a really object oriented heavy another thing is that nest is built on top of express so if you have experience with express which is by far the most popular node.js framework then nest should be a little bit easier for you yes there's going to be some nuances there's going to be some differences but nest should be relatively easy at the end of the day we're just building an api and it's also optionally configured with fastify if you wanted to but i think most people are more familiar with express now express what it does is it's really great but it really gives you kind of the bare bone and essentially what nest does is it really provides a level of abstraction above these frameworks and it gives you a really great way of organizing and separating your concerns so this is what we're going to be doing i'm going to try to cover as much as i can i'm going to probably cover everything here in the documentation but i'm i'm inevitably going to miss something so feel free go to go to the nestjs.com documentation and give it a read it's really thorough and really great now in this application we're going to be building an api and we're going to be building a very very simple api so over here we basically are building an api that allows us to get teachers and they're associated students so here are the the eight different routes that we are going to be building so over here we have a get route which is just slash students and this is just going to get all of the students regardless of their teachers this is a get route that is going to get a specific student based on that student id and this is a post route that is going to create a student and we're going to basically pass the data in the rec.body and then over here this is a put and the put actually i'm actually missing here this should also have student id and essentially what this is going to be doing is it's going to update a specific student by that student id and we're also going to add the data that we want to update that student with in the request body and then over here we're going to start having the teacher routes over here we have slash teachers that just gets all the teachers this gets all the teachers with a specific id this gets all of the students that are associated to a particular teacher and lastly what this is going to do is going to update the student of update the student's teacher to whatever this teacher id is over here so if that doesn't make a lot of sense don't worry too much about it but this is really just a simple uh a rest api that we are going to be building with nest js now if you ever feel stuck or if your code isn't working for some reason feel free to go to my github page uh in my github page i try to do the best job to organize basically what i am going to be doing so if you want you don't have to start in the main directory or the main uh repository you can basically go into different branches if you want to and that basically what what that basically does is it kind of eliminates uh let's go over here like it kind of eliminates all of the extra work if you're not there yet so for instance if you go we're starting off with controllers you can see that we have uh this little code over here so you can try to follow along as much as possible through navigating the branches so i'm super excited this is a great node.js framework i'm actually using it at work and i'm loving it thus far so i hope my explanations are good and hopefully you enjoy this framework okay so the first thing that we are going to cover is creating a boilerplate nest js project and thankfully this is really really easy we just have to do a few commands inside of our terminal now how do you know what these commands are well you can go to the documentation and it says here that we are going to be using the built in nest cli in order to create our nest application so the first thing is you need to install the nest cli so let me just zoom in here a little bit the command to install the nest cli inside of your local machine is npm i or install and then dash g for the global flag and then at nest js slash cli so go ahead and run this inside of your terminal i already did and this actually takes a little bit of time so i'm not going to go ahead and do it again but you run this right now in your terminal and of course you need node js to run this because we are using npm and then what you can do is you can just do nest dash v to check the version of nest that you have installed and this basically ensures that hey yes you have nest installed so if you have any sort of number over here whether it's higher lower exactly the same that means you have nest installed the nest cli installed in your machine if you get some sort of command saying hey nest not found command not found then no you probably didn't install it correctly so go ahead and install this now mind you if you are on a max or linux you might have to prefix this with sudo and then input your credentials your password all right and then the next thing that you have to do is run this command over here so we're using the nest cli so nest and then we're saying new basically symbolizing we want to create a new project and then we're just going to give our project a name so let's go ahead and do that right now so we're gonna do nest new and then we're gonna give our project nest app so we're gonna call it nest app i hope this is uh large enough there we go so once you execute this command then you're going to basically be prompted with a question hey do you want to use mpm or do you want to use yarn i'm going to stick with mpm because that's probably what most people do i actually do prefer yarn over mpm but i'm just gonna stick to npm just in case people don't have yarn installed on their local machine but honestly you can pick either or so you can go ahead and do that and what i'm actually gonna do is i'm just gonna cancel it because i already installed this app boilerplate so i'm not going to go ahead do it again because again it would take too long so if i do ls what it will do is basically create an app for me inside of my local directory so this is the app that we just created and i actually didn't fully install it so uh it's not actually not fully complete but then this this is the app that i actually installed beforehand so this is the one that i'm going to be using and so if i go cd my nest app well now i'm inside of that directory so i can go ahead and open that and if you have vs code you can actually open up with code dot and what this is going to do is going to open up in your vs code text editor if you set this up of course if not then just go ahead open up vs code or whatever text editor you're choosing navigate to your nest directory and open it up now i already opened it up and i'm getting an app that looks a little something like this so you can see here that you have a lot of boilerplate and we're mainly going to be discussing everything inside of the source directory so over here you can see here that okay inside the source directory we still have a lot of things we have the app controller.spec.ts this is just a bunch of test files we have the controller okay what's going on here we got the module we also have the service and then we also have the main dot ts and we're going to talk about all of these files and more so don't worry all too much about it but for now what i want to do is just clean up this source directory a little bit so what i'm going to do is i'm going to remain i'm going to leave the main dot ts and the app.module.ts i'm not going to touch them but everything else i am going to delete so let's go ahead and let's just delete them for now so i'm just going to delete this this is the test file we're going to delete the app.controller so let's go ahead and not rename it let's delete it completely wipe it out of existence and then let's also get rid of the service as well so the app.service.ts and what i'm also going to do is i'm going to create a directory called app and i'm just going to place the app module inside of that directory okay so uh but now what i'm going to have to do is i'm going to do some fixes okay because over here you can see that the app dot module is actually using the app controller and the app service which we just deleted so let's get rid of that and what's great about typescript is it tells us everything that is going wrong let's also get rid of the controllers and the providers as well let's save that and then inside of our main dot ts file what we're going to have to do is fix this over here because remember we put our app.modules.ts inside of the app directory so now what we can do is something like this so move into the app directory and then move into the app modules so i'm going to talk about the modules in great great detail but i'm going to just quickly illustrate this right now just what's going on right over here so in here we have this app module and you can really think of this as the root of our application again you don't have to worry about what it's doing just know that the app.module.gts is the root of our application and it should have basically all of the logic of our applications imported into this app.module.ts now inside of the main dot ts essentially all that we're doing is bootstrapping or starting up our project so you can see here here we have const app and we're basically creating our nest application using the nest factory and so this is asynchronous you can see here using the nest factory we're creating a nest application and we're passing into it the root of our application again don't have to worry about what it does now i'll explain that in great great detail but we're basically passing in our application the root of our application which is the node modules so what that's doing is going to create a nest application with this right over here with this root and then what it's doing is it's basically running that on port 3000 and so essentially we're basically running our application our nest application on port 3000 and this is just a function and we're just calling it right over here so that is what we are doing and that is just basically what we're going to be talking about now that is the boilerplate in the next section we're actually going to start working on our apis we're actually going to start creating each and every route and we're actually going to be able to test each and every route on postman so we'll get to that in the next section let's start creating the api routes that we have discussed right over here now in nest we do that through something known as a controller and let me quickly explain what a controller is so simply put a controller is something that accepts http requests and sends back a response to the client and that's all it's doing all of the business logic associated to manufacturing that response is not housed inside of the controller it's housed somewhere else so the controller is ultimately going to make a call and basically call that function but it's not housed inside of the controller itself all the controller is responsible for is accepting http requests and sending back a response and in our application we can have multiple controllers so let's actually kind of go through a flow so over here we have our client and let's say our client wants to get all of these students so it's going to make a get request to slash students so what this is going to do is going to be forwarded to a specific controller that's going to handle that request so let's say that that controller is this blue one right over here so it's basically going to get this request and then it's going to return a response with all of the student data that's all the controller is doing again let's see here we have another request let's say that we want to get all of the teachers then what we're going to do here is we're going to make a request to another controller that's handling basically all of the teachers and it's going this controller is then going to send back a response with all of that teacher data now a controller is not only uh basically subjected to just one route so over here we have basically another uh basically routes that we want to make and this is getting one student and essentially what this is going to do is going to go to this controller over here and again the logic that is housed to get this is not going to be inside the controller but this controller is going to call the function that's going to have all the logic to get that student but then once it gets that data it's going to send it back to the client but as you can see here that this controller is actually handling multiple routes and it doesn't also even have to handle just get requests one controller can handle 10 or 20 or even a million routes as much as we specify and they can handle get requests and we can handle post requests and we can handle delete requests but typically a controller is going to house routes and are going to deal with routes that are common for instance here we're basically dealing with students so you can see here this is slash students that's getting all the students and that's why it's dealt with in this controller and this is slash student student id that's getting one student and so it's basically housed by this one controller that's dealing with all of the students over here this is dealing with teachers so it's going to be in a different controller okay so i hope that makes sense but the best way to learn is through practice so let's actually go ahead and let's create this controller so to create a controller what we're going to do is let's start off with the student controller because we're going to create a bunch of student routes so we have you know the the slash students slash student id slash uh students for a post request and slash student dot id or colon id and this is basically an update now over here where this is right here is going to be housed in one controller because we are really just dealing with student routes here so it makes sense to create some sort of student controller so to do that what we are going to do is we are going to create a new directory not inside of the app.js but inside of the source directory we're going to call it student and this is going to basically house our student controller and all the other student related things that we'll eventually add in there so in here what we are going to do is we are going to create a student dot controller dot ts so student dot controller dot ts now in here we have to specify that we are going to create a controller so how do we do that well we do that in nest through something known as decorators so decorators are very important because they basically identify what the thing that we are trying to create is and it actually gives it a lot of metadata that is required for its functionality now how do we get the decorators well the majority of the decorators are going to be inside of the at nest js slash common module and this is all automatically installed for us when we have created our nest project with the nest cli so in here we're going to take the controller decorator so the controller decorator right here so we're going to basically import that in now a controller is basically a class that is going to contain a bunch of methods and these methods are going to be called for specific routes so we're going to create this class and we're going to call this class student controller so we're going to call this class student controller and we are going to decorate it with the at controller decorator basically signifying that hey this is a controller this is going to tell nest that this is a controller class so to do that you would do at controller at the very top and we would basically call it right over here so now we have our controller so this is our student controller now in here we are basically going to define all these routes right here so we have the get students we have the get student id post and the put now one thing in common with all of these routes is that they all start with students they all start with students so what we can actually do inside of this controller decorator is say that hey these all start with student so now basically what's going to happen is every single method inside of our controller is going to start off with slash students so slash students which is terrific because again everything in here well starts with student anyways okay so now let's actually start creating our actual routes so how do we do this well it's actually not that complicated so let's begin with the very very first one which is the easiest one so again what we're doing is for each route we're creating a method that we're ultimately going to call so let's actually start off with this first one right over here so this is going to be the get students route so this is the get students route so once we hit basically just slash students then what we're going to want to do is basically get all of our students and we're going to return some data so we're going to return some data and for now i'm just going to say all students obviously we're going to want to return an array of all of our students but for now i'm just going to return the string so that is the method that we are going to call with this request over here but how in the world is it gonna know that hey this is a a get request because we know that okay this control is going to handle slash students but how do we know that this is a get request or a post request or a delete request well we can basically specify this through a get decorator so we have the get decorator so right over here we can basically say get so right on top of this method we have the get decorator and nest is smart enough to know that okay well if we have a get request that is slash students then forward it right over here to this uh to this method and basically return this data return whatever data that it ultimately returns so let's actually give this a shot all right so now of course this is actually not going to work right away and the reason for this is our application actually has no idea that this controller even exists so remember our app.module.ts that's basically the root of our application and it has no idea that this file even exists so what we somehow have to do is tell our app.modules.ts file that hey i want you to actually use this controller now to do this what we are going to do is we're going to specify inside of this object right over here and this if this doesn't make sense to you don't worry we'll cover modules in great detail but for now inside of this object there is going to be a controller's key that we can specify and this is going to take in an array of all the controllers that we want so what we can basically do is export export this controller and basically import it into this file and then put it into this array so let's go ahead and do that so let's go ahead and let's just export this out let's save that and let's go ahead in here we're going to import our student controller from these in the students directory the student controller and we want the student controller so now we can basically go in here and we can go ahead and save that okay terrific now we actually have to go ahead and run our application so let's go ahead and run it right now so i am opening up my integrated vs code terminal and to run our application let's take a look at the package.json so in the packet.json we have a bunch of script we have pre-build build format now if you want to actually start your application highly suggest start colon dev and this is basically going to run our application but it's going to run our application in watch mode and basically what that's going to do is if we make any change we don't have to restart our application it's automatically going to catch those changes and configure our running application accordingly so let's actually do that right now so let's do mpm run start colon dev and this should run our application on local host 3000 so let's just wait a little bit it shouldn't take too too long and now once this is up and running and it is up and running i want to test this route and so the best way to test routes in my opinion is through postman so i i absolutely love postman let me get rid of this right over here because i'm going to be going back and forth with postman a lot postman is basically a way to uh test out our api routes so let's actually figure out what we want to test so again what we're going to be testing is the api which is going to be running in localhost 3000 and then slash students because that's what our controller is specifying so if i were to execute this you can see here that i actually get back all students which is terrific because that's exactly what we want let me quickly zoom in just in case you guys don't see it but right there that is exactly what we want which is which is great all right so now let's actually move on to the next route which is unfortunately right over here there we go i actually do so the next route is going to be slash students and then over here we're gonna have basically a dynamic parameter the student id okay so how do we tackle that that one's a little bit trickier okay so let's talk about how we do that so in the student controller what we are going to do is we are going to specify a method this is the method that's going to be called when uh when basically our client is making this http request so this is going to be get student just one student by id so this is the method that we're going to call and for now we're just going to return uh we're going to return get student by id and let me capitalize student for consistency and we know that this is going to be a get request so for sure we're going to have the at get decorator but at this point these two routes are exactly the same and they're actually clashing what we actually want is slash students and then slash so slash students and then slash whatever that student id is now to specify additional basically paths additional paths to the the the core one that we have over here we would add that inside of the actual decorator the the request decorator right over here and so this is basically where we would add it and so essentially now what we are going to be doing is adding that in there so let's go ahead and let's do that and so basically now what we're going to be doing is slash colon and this is just basic uh this is just basic express slash students or slash student id so slash student id and so essentially here all we're basically doing is we're saying that hey this is going to be slash student and then slash a student id and again this is a dynamic row because we specified the colon right over here so if i were to save this now and i were to make this request so slash student slash this is an actual student id and if i were to send this off uh it fails for some reason which is strange i wonder why that slash student slash student id invalid regular expression let me quickly save this again i'm actually a little surprised that that failed oh the reason why it's filled is because i just left this over here okay that's why i failed all right so let's actually go ahead and let's uh send this request off again you can see here get student by id okay terrific terrific terrific so now let us quickly breeze through the other ones because we still have six more to go which is pretty insane uh so now let's do the post request and the put request and this should be very very similar so for the for the post request again we're going to create a method and this is going to be called create student because that's what we're doing we're creating a student and now we're just going to return for this we're going to return just create we're going to return create student now over here this is not going to be a get request is going to be a post request so now what we can basically do is just do slash post and then we can do act post the decorator right over here so now again if we go here you can make this request and of course it fails for some reason uh because i didn't save it so let me save it and now if i were to make this request again you can see here create student all right so for the last one for the student controller is the put so let's actually get this decorator is the put and by the way there's more methods of course there's patch if you want to use that there's delete i believe there's also all so there's more if you want to use them i'm just going to cover these these uh these three so i'm going to say act put and then i'm going to do update student and then i'm over here i'm just going to simply return update student by id update student by id and again this is a little bit more complicated because again we have to specify a random url right over here a random param so to do that simply you would just add it inside of this request object so we're going to add that in there okay so terrific so that's pretty much it and you can see here the controllers all they're doing is they're getting resp they're getting requests and they're sending back responses so that's pretty much it for this now let's actually quickly work on these ones and i actually highly suggest that you pause the video and try it out on your own because this is going to be extremely similar now there's going to be a little bit of a change in the last two but again i highly suggest that you go ahead and try this on your own i'll give you five seconds to pause the video if not then you can continue following along and see if you got the answer right so five four three two one okay cool so let's actually go ahead and create this controller now one thing that i want to note is that uh creating controllers can be relatively repetitive you know we're gonna have to import the controller and then we have to create the controller and then we're gonna have to create this class controller can get pretty repetitive and you know what the cli is actually really great and it knows that it can get repetitive and then so basically what we can basically use is the cli to create our controllers for us so to create a controller we can actually go to the documentation so we can go to the express documentation or the nest documentation rather and in here if i zoom out a little bit you can see here that we can actually create a controller through this command nest generate and then we want to generate a controller and then we're going to give our controller a name so let's actually go about doing that right now so let's do nest so let's do nest g for generate and we want to generate a controller and we're going to generate a controller with the name of teacher and i'm also going to specify the no spec flag and this basically ensures that it doesn't create any test files for us so it just creates the controller so let's go ahead and let's execute this let's give some time okay so we can see here that it has created a controller and not only has it created the controller actually it created the directory created a teacher directory and in here you can see that we have a teacher dot controller so you can see here that we have all of the boiler plates for us already made which is really great now one thing that i want to change is i want the path to be slash teachers not teacher so i'm going to just change that to teacher and now what we're going to do is we're just going to create the rest of the route so basically all of these routes so let's go ahead and let's do that quickly together so the first route is going to be and let me just quickly open up uh the code in my other machine so i can follow along okay so the first route is going to be at get and so you notice that i actually auto imported it which is pretty cool so at get and this is going to be get teachers so we're going to get all the teachers and we're going to return all teachers so we're going to return all teachers the next request is going to be at get and then this is going to get a specific teacher by id so we're going to get a specific teacher by its id all right so over here of course we have to specify we have to specify the teacher id all right so what are the next paths well now we're we're actually start dealing with some of the paths that involve the students so let's go ahead and let's create them so remember we have the uh get all students that are associated to a particular teacher and so let's actually just copy this and what we're going to do now is we're going to do this is going to be slash teachers slash teacher id and then slash students and so we're going to call this we're actually going to call this get students that's what we're going to do we're going to call this get students and then lastly we're going to have the act put at put and then this is going to be update a student teacher and so to basically call this function we're going to need all of this right over here so we're going to need the teacher id and then we're going to call the students param and then slash student id okay so that is what we are doing right over here now one thing that i want to note is that this these two routes are getting quite similar you can see that they both start off with colon teacher id slash students call in a teacher id students now it's perfectly acceptable for us to leave it over here if we want to but let's say our file continuously grows and grows and grows and grows and we have actually a lot of routes that are just slash teacher and then slash colon id or slash whatever and then we also have a lot of routes that follow kind of this trajectory slash teacher id slash student slash teacher id slash student it actually might be good to separate that into a separate controller especially that these two routes are actually dealing with students really so it might be a better idea that in this teacher directory to actually create another controller that deals with all of these student routes that are associated somehow in some way with teachers so let's actually create another route right over here or another controller and we're going to call this controller student.controller.ts and we could have definitely uh generated this uh controller inside of the nest cli but uh it's all right we don't have to do that so now what we have to do is we can basically just copy and paste this let's just copy and paste the whole thing and what we're going to do is we're going to call this student teacher controller and we're going to get rid of this over here and we're just going to leave these two and we're going to get rid of these two right over here and you can see that that really cleans up our file actually which is pretty cool so now what we can actually do is basically say that hey this is always going to start off with slash teachers slash colon teacher id slash student so now we can actually completely get rid of this because that follows that path and basically here we can just say that hey this is just going to append slash colon student id and now one thing that i'm forgetting is of course the returns so let's actually add those in real quick so we're gonna over here just return some data so we're gonna return get all students that belong to a teacher so this is getting all the students that belong to a teacher unless over here we're going to quickly return update student teacher because we're updating the student's teacher for this and then lastly for our student controller i'm missing over here get so over here we get teacher by its id okay terrific now again our application actually has no idea about these routes even though we saved them so now if we go ahead and we try to execute this it's still going to fail it's going to say hey well there's no route found so to fix this of course we have to tell our our app.module.ts about our controller so we're going to have to import them in so let's go ahead and let's just quickly import them in and so this is going to be slash teacher let's get the slash teacher controller and we can basically pass it in right over here and similarly let us get the slash forgot that what that one was called it was a slash teacher slash student i forget it was slash student teacher controller so let's actually put that in there as well so let's put that in there as a a controller terrific so now what we can basically do is actually go ahead and make these requests we'll start from the beginning get all students get those students by id create students update student by id now we can get all of our teachers slash teacher slash the id is get by id and then over here slash student a slash teacher slash the teacher id and then slash students that's going to get all the students that belong to a teacher and then lastly slash student slash the teacher's id slash student sorry slash teacher slash the teacher id slash student slash student id that's going to update the students teacher so that right there is controllers i know hopefully that wasn't too too too confusing i know that was a lot uh but uh i hopefully try i try my best to kind of explain as as well as possible so hopefully everything is is really really clear now in the next section what we're going to want to do is we're going to actually want to start extracting uh these ids because we're going to definitely need to use them in order to send back a proper response so we're basically going to figure out how to do that through something known as request object so we're going to do that in the next section now that we have created the api routes let's talk about a way to extract the important pieces of information from the request itself now what am i talking about here well let's look at this route right over here this route is responsible for getting a specific student based on the student id that we pass in as a param right over here and so we need a way to actually extract the student id use that id to get the correct student now as a quick reminder the actual route would look something like this so localhost 3000 students and then slash that student's id that we're trying to get so we basically need a way to extract this student id from that request and use it in our function and eventually get the the appropriate student now the param itself is not the only thing we could also have things inside of our request body for instance when we want to create a student we're going to pass data inside of the request body and we need a way to extract that data and basically use that data to create that student so over here this is how the request body would look like when we want to create the student it's going to have a name and then a teacher id because we're going to associate a student to a particular teacher but again we need a way to extract this out now how do we do that well we do that in nest through request objects so let's talk about that right now let's actually begin with this one right over here where we extract the id from this particular route okay so this right here so this route is response is basically uh being handled by this function right over here and we need a way to get this student id well again we're going to do that through request objects and request objects are just decorators so one quick thing when we want to extract something from express typically we would have something like request and then we would have response and then over here we would probably do something like uh would you structure out the student id from the request parameters now in nest the concept is actually a little bit different in in the parameters themselves we actually specify what we want to get out and then we can basically use that so we if we want to get out some parameters then we get out some parameters using the request object that is param if you want to get some body then we'll use the body request object let me quickly explain what i mean by actually doing it that will make more sense so the first thing let's say we want to get out some params well we use this request object and this is just a decorator so in here we basically say that hey from the request we want to get the params so we basically want to get the params and we can basically say params and we can give this param a type now this is going to be of type object and then it's going to have inside of that object a student a student id that is a string so now basically what we can do is use that param inside of our function and to quickly illustrate this let's actually just console.log the param so we're going to console.log the param and i'm going to call this params because we could have multiple parameters in there okay so let's give this a quick save and let's actually go ahead and make this request so get student by id and remember this is the id right over here now if i go to the console you can see here that i have an object where the key is student id and then the string is well the id itself so that's terrific and again we if you have multiple things inside of we have multiple params inside of our route we would have a bigger object with everything else now let's say we just want to destructure out the student id we really don't need this object so one thing of course that we can do is something like this so we can just destructure it out and we can say student id well there's actually a better way of doing that with nest and we actually don't have to do this extra layer of destruction out inside of the param we can basically ask for what we want so we can say that we want the student id and then over here this is not going to be the whole param object anymore it's actually just going to be the student id so basically what we can do is call this student id and simply this is just going to be a string so now what we can do is we can go ahead and save that and now if i were to make this request again you can see here that i'm console.logging just the id all right so this is terrific this is this is awesome so now we know how to extract basically the params from the request okay so let's just quickly change this right now we're going to change this to get student we're going to say with id of and then we're going to say student id and i'm going to get rid of this console.log because it's not really needed anymore okay so now if i make this request you can see here that we're getting the student with this id now if i were to change this of course then you can see here that it changes accordingly all right terrific okay so now let's start talking about the post request so remember the post request the data is going to live inside of our body so for this we're going to use the body decorator so body decorator so similarly to the param we can basically say that hey we want the body we can call this body and for now i'm just not going to specify a type oops we're not going to put this in the in the post decorator we're going to put this in here in in the actual uh function or method decorator so or in the parameters itself so we're going to say here that we want the body and basically the body let's actually just quickly console.log it and let's go ahead and let's send off this request you can see here that we have a name of ben andrew and then the teacher of this id all right terrific and again we can always extract what we want so for instance if we want the name we can change that to name and then change this back to name and so if i were to send this off you can see i just get the name now for the body uh typically we get the whole body itself we actually don't extract it out and i'll actually show you why that is in a few sections from now it's actually it's actually a pretty important uh and pretty important thing pretty important concept in in nest and actually it ties to the type of this uh particular body now i'm not defining the type but we're going to do that a little bit later on through something known as dtos but we'll get to that a little bit later so okay so now that we got the body let's actually go ahead and let's just quickly change this so we're going to create a student with the following data and the data is going to be json dot stringify and then the body itself the reason why we're stringifying it is just so it is it produces a nicer output uh when we uh when we actually try to output it over here in in postman okay so that is great now let's actually do the put request so the put request is pretty special because in the put request we're going to have data inside of the body as well as data inside of the params so over here we're actually have kind of a double whammy we have the body as well as the params well this is very easy still so all we really have to do is just param and again from the param we want the student id we can specify this as a string we can specify that as a string okay terrific uh oops nope that's not how it goes of course we will have to define the variable and then specify that as a string and then we also want the body and we'll define the type of the body later don't worry so let's actually go ahead and change this this one's going to be a little bit longer and of course we're not all going to return strengths we're actually going to turn real responses a little bit later on but for now i just want to kind of illustrate this by just returning string so update student with id of uh student id with data of json.stringify and then the body all right so now if we update the info we can see here update student with id of this with this data right over here okay so now it has come to the point where i highly encourage that you do the rest so i highly suggest that you pause the video and basically do the rest over here so for the get teachers it's fine we don't need anything but for the get teacher by id we need to extract this from the params for the get teacher by student id we actually have to extract two params so we have to extract the teacher id actually no we actually just have to extract the teacher id it's the puts request that we're going to need to extract the teacher id as well as the student id so this is the teacher id this is the student id okay so i highly suggest that you do it if not i'm going to quickly do them right now okay so let us go to the let's close this off let's start with the teacher module and in the teacher module we're going to have our parameters of course so over here we're going to do at param and notice that it auto imported and then this is going to be called teacher i hate how this is so big teacher id and then we'll call it teacher id and this is a string and we're just going to quickly change this to get teacher by or with id of teacher id all right terrific so that should be it for that one and then let's go to the student controller inside of the teacher directory and then here okay here it's a little bit more complicated so here actually we have the teacher id uh so in here we can basically specify the app param and we can basically get that teacher id so teacher id teacher id which is going to be a string of course and then uh let's see here let's uh get all students that belong to a teacher belong to how about the teacher with i don't know why i decided to capitalize all this but it's too late now with an id of this all right so the absolute last thing that we need to do is this one and this one you might think it's complicated but it's really pretty easy and i i i bet you can probably figure out how to do this we're gonna use the param twice so let's actually just copy and paste this so we're going to get the param for the teacher and we're also going to get the param for the students all right so now last thing we have to really do is just update the text and so we're going to say update students with id of uh and then we're going to say student id to teacher with id of teacher id all right so terrific so now we actually have a way of extracting data now there's actually a lot of different things that we can actually do i highly suggest that you go to the nest documentation to see exactly what you need so let me quickly just zoom out of this and try to go back to the over here so inside of the controllers you can see some of the different request objects that we have access to for instance we actually have access to the request the whole request itself and we can do that through the add to request decorator if you want the whole response then we can do at response if we want the next function that we're going to talk about actually when we deal with middleware so you don't have to worry about that we can do at next if we want the session at session param we talked about the param we talked about the body we can also do queries as well as well as headers so sometimes we actually have maybe an authentication token in the header we need to have access to it um these other ones never really used ip but i mean in these cases where you have to use them go ahead that's how you do it so in this crash course we're really just dealing with these two as well as the next but again like you you have the ability to extract the request header if you want to or the request query so that's pretty much it let's just quickly test that everything works uh okay cool that works that works and that works and i believe we tested all the other ones all right so that is request objects let's start talking about something known as data transfer objects or dtos for short and to kind of explain them let's go through an example right over here now inside of the student.controller.ts file in the student directory we have our post request and the controller is extracting out the whole body from the request itself and then once the controller extracts the body what it's going to do is it's going to send off that body to something that is going to have all of the logic to manufacture and create that student and so essentially this this body isn't going to be passed down to another component now the problem here is we don't really know the type of this body that is something still very unknown to us now what we could potentially do is something like this we can just do something like the body has a name of string and a teacher of string so a name of string and a teacher of string we could very well do this or we could even go the route of just extracting at body and we can just extract the name so we can extract the name which is going to be the name and then that will be the string and then the same thing for the teacher however there's kind of a problem with this approach the data will be consistently changing it might change for instance now we want to name the teacher but later on we might want the grade so we might also want the grade which is a number so we also might want this so if we're doing this route then we would have to add this type over here if we're doing this route then we would have to add another field and then we would also have to manipulate it inside of our service as well which i'll talk about a little bit later but that's the thing that we're ultimately sending that body into and that's not that's not that's not that's not clean that's not nice we don't really want to do this so instead of doing this what we do is we create something known as data transfer objects and these are just classes that really just define the type of the data that we are consistently going to be transferring to because we're going to be transferring the data from the request to the controller and then the controller to something else that's something else is the services which we'll talk about later but we're consistently transferring the data and that data might change so it might be better to actually externalize how that data is going to look like through data transfer objects and that's what we're going to be doing so again best way to actually learn about it is to just practically do it so to create a data transfer object in the directory where you want to create the data transfer object in then create a folder called dto so dto and then in here we're going to create our data transfer object so let's actually create the first data transfer object we're actually going to create them for every single one but we're also going to let's start off with the post request because that's the request that i i made so essentially here what we're going to do is inside of this directory we're going to create student dot dto dot ts and in here we're going to create a class i'm getting some sort of error here i guess i am getting in there let's see why that is right here oh that's because i completely wiped out the body this is definitely not what i want let's just wipe put that ray back in there cool all right so now in i always forget don't put it in here put it in right here there we go cool okay so now inside of the student.dto.ts what we're going to do is we're going to create a class and we're going to call this class create student dto and this is basically going to be the body that we're going to need to create our student and so over here we can basically say that hey the name is a string and the teacher is also a string so the name is a string and the teacher is also a string this is a class so we don't uh we don't have commas it's actually just colons each line is separate and then what we're going to do is we're going to just extract this out and so now what we're going to do now what we're going to do is inside of the student controller we're going to import that dto so we're going to import that dto and that's inside of the exact same directory slash dto student dto and where are we and then yeah so this is going to be called the create student dto and essentially what we're going to ultimately do is we are going to define this body to be the create student dto all right terrific and then uh similarly we're going to want to create a dto for the uh the the body of the put request now you might say okay we could potentially use this body as well but maybe later on in the future what ends up happening is for the put and the create dto we have different needs and different requirements from the body so we don't want to use this one over here even though at this moment we are extracting both of the uh the name and the teacher from the body but again later on in the future we might not want to do that so what we're going to do instead is just create another class we're going to call this update body update student dto we're going to save that and notice that i haven't imported it in but you can just auto import it by just straight up just using it so we can just say update body actually guess i guess that didn't work as well as i wanted to updates or update student dto so i guess that was probably one of the reasons update student dto all right terrific so this is great now one thing we also want to do is we want to define the type that the method is ultimately going to return right now this method is returning a string but ultimately it's not going to be doing that for instance here it's going to be returning this get students is going to be returning an array of students so also in here we're going to have to create a dto for this and this is going to be a dto that sends back a response so we can basically say something like export class and then this is going to be find students response dto and then this is going to be well we're going to go ahead and actually we're going to change this to find student dto and then we're going to say that hey you get back the id which is a string you get back the name which is a teacher or sorry sorry the name which is a string as well and a teacher that is a string there we go again we can go ahead and just use this now so over here we can just say find student dto we can basically say that hey we're going to return back a student response and this is going to be an array now you're going to start getting some typescript errors because while we're returning a string but we're expecting to return this that's completely fine we'll work on that a little bit later similarly over here this is going to return just one student so what we can basically do is say that hey we're going to return one student this is ultimately the post request it's going to return the student that we create so that is going to be very similar it's just going to be just one student and then for the update student we're also just going to return the student that we that we ultimately want to return however it actually might be a good idea to actually create a separate uh a separate dto for this as well so it's actually creates if if this isn't a find students here we're just trying to find students here this is just the student's response for the post and the put request so it might be a good idea to just have a separate dto we're going to call this student response dtl we're going to go ahead and save that and let's go ahead and just import that in because again these are just fine student responses where these are just student response dtos we're not really finding anything so we can go ahead and just add that in there okay cool so now we actually have a lot of good typing and you can see that typescript is yelling at us uh which is which is good this is ultimately what we want and now we can basically pass this information uh from our request to our controller from our controller to our service a lot easier and if we ever need to change something then we can just easily change it inside of the dtl okay so that is pretty much it now if i do save this i'm going to get a bunch of errors and actually the code is not going to work but now let's just quickly create dtos for the teachers so that is going to be the next step and then and then what we're going to ultimately do is we're going to start fixing all these typing through services so i highly recommend again as always to uh pause this video and uh try it out on your own because you know the the best way to learn is to actually try it out and do it yourself however if you don't want to do it then completely fine i'm going to continue on and i'm gonna start doing it right now okay so let's begin let's just close everything off so now we need to create the dtos for the teachers so the dtos so we're gonna create a dto file a folder and in here we're going to create teacher.dto.ts so teacher.dto.ts and let's just begin with the teacher controller now the teacher controller is going to house um it's going to house basically the get teachers and then they get teacher by id now over here we basically want very very similar dtos to the ones that we have created back in the student controller so here we basically want a find teacher dto response and so let's actually go ahead and let's create that ring now okay so so for the find teacher what we're going to do is we're going to create a class so we're going to do export class export class and this is going to be a uh we're going gonna call this find teacher response dto so find teacher response dto and ultimately for the teacher we're just going to return the teacher's uh uh id as well as the teacher's name so the teacher's id as well as the teacher's name which is a string and so here what we're going to do so this is defined teacher dto so here what we're going to do is we're just going to copy this and then we're going to import that in here and this one's going to be relatively easy because there's nothing really in there in the request body or anything like that so teacher and so we're just going to define that hey this type is going to be an array of fine teacher dto response uh and then similarly over here this is just going to be one so we can go ahead and do that okay so this is uh this is pretty great so far so now let's actually work on the student controller so the student controller and this is actually going to be very very similar to what we had uh before we're actually going to recycle some of the dtos that we have used because this is ultimately just returning all of the students even though it's returning all the students associated to a teacher so now what we can do actually is just recycle some of the dtos that we created inside of the student directory dto so the uh the first one we're going to use is defined student response dto and as well as the student response dto so this is defined student response dto and so over here we're just going to say that this is ultimately going to return an array of this and then for updates well this is where we're going to use the student response dto because we're just going to return the student with their updated uh teacher and so we can just return this okay cool so again everything is is basically on fire right now like everything is is breaking and that's really good because that's ultimately what we want we want typescript to to tell us if we're not really defining or not really returning the correct uh uh data structure and so this is this is really good this is ultimately what we want okay cool so that is pretty much dtos and uh i hope i hope that kind of clears it up in the next section we're actually going to start fixing all of these errors through services let's start fixing those typing errors and send back responses that actually make a little bit more sense than the strings that we have been sending now remember the way to manufacture the response that we want to ultimately send is not going to be housed in the controller itself but rather it's going to be housed in something else known as a provider and that's going to contain all of the logic that is going to send back the response for instance if we want to send back all of these students then we would have some sort of provider or in this case the provider is going to be called a service and this service is going to get all of the students from our database or wherever we're storing them do some sort of sanitization whatever it is it has to do and then send that data to the controller and then the controller is going to send that to the client so let's actually start doing that by creating our services now if you want to learn more about providers what you can do is you can go to the documentation and essentially we're going to be using providers as a service so over here we have mo there's multiple definitions of providers but we can have services we can have repositories we can have factories but we're going to be using services because services are going to be the thing that ultimately serves us and manufactures the data so let's go ahead and let's do that right now now a way to do that is we can actually go ahead and just create another service but i'm going to use the nest cli so i'm going to do nest generate and then service and then i'm going to give the service a name and the service is going to be let's start off with these students so it's going to be the student and i'm also going to specify no spec so i don't get any of the test files all right so now if i open up this directory you can actually see that i have a student.service.ts all right cool so now in here we're actually going to have all of the logic that ultimately serves these routes right over here so these routes right here so let's actually start off with the get student now let's actually just quickly examine the service itself so you can see here we have we're getting this injectable decorator and we're decorating it with uh we're decorating this student service with the injectable decorator and this basically is important because essentially what it does is it marks this class as a provider and that's very important because it provides it with the necessary metadata all right cool so let's actually go about doing this right now so let's let's create the service that ultimately is going to return all of the students now to return all of the students we need to have the students somewhere stored maybe in a database so maybe we can use postgres or mongodb this is not a database course so we're not going to use any sort of database or orm we're just going to simply very easily just create a database dot ts file inside of our source directory and this is going to be our source of data now to get the data you can just go to my crash course right over here my github page nest crash crash course and go to the main branch and then just go to source and then go to db.data and i have just a bunch of student data and as well as some teacher data so i can just go ahead and copy this and then just paste it in there all right so now let's actually start creating the service that is ultimately going to return all of the students so this one's uh relatively easy actually so let's go about doing this one right now so the student service so the first thing that we're going to do is this is going to be a method that we're ultimately going to call so this is a method that we're ultimately going to call and typically this method is actually exactly the same as the method that we have inside of our controller so we can basically do get students and then over here we can have all of the logic to get all of our students now this one's going to be relatively easy because well we're just getting all of the students straight up now what we're going to do here is we're actually inside of the class we're going to get this data over here and just put it inside of this class so we're going to do something like students is equal to is equal to and let's export out these students from the database so we're going to export out the students from the database we're going to say students is equal to students so now we basically have access to so we have access to this dot students so this dot students and this is just basic uh you know just just class classes and object oriented programming essentially here we can basically inside of our method we have access to the students because well this is inside of the class itself now one script that one thing that we could do with typescript is say that hey we don't have access to this particular um to this particular uh property outside of the class itself so if i were to ever instantiate this for some reason if i were to do cons students is equal to new students new student service so if i were to do that right now if i were to do student and i should just change this text actually just to clarify this if i were to do student dot i would actually get students and i would really never ever ever really need to get the students i want all of this to be handled by our methods so what i could possibly do is just say private and then that way now we can only say get students and we can't really say you know get uh or sorry yeah so x dot gets students rather than x dot students okay cool all right and we could also mark this as read only if uh if we didn't ever want to manipulate this but we are ultimately going to manipulate it so we're not going to mark it as read only so there we go we have created our first service so now what we can do is we can actually use this service inside of the controller now to do that what we're going to have to first do is basically go to our app module and tell our root application about the service itself so we have to tell our application that hey we have a service and the service is a provider ultimately and we can basically import that so let's go ahead and import the service that we have created let us go to this is app student where do we put this right here service and then we're going to call this well well we already called it student service and we would basically pass that in there and i'll show you why that's important right now actually so to actually be able to use the service in the controller what we ultimately have to do is actually put it inside of our constructor so we can basically have a constructor right over here and basically inside of the constructor what we can have is the uh basically the student param and so we can basically mark this as private if we want because we're not going to use it outside of this class we're also going to say read only for this so private read only and we can say student service so how in the world is it going to know that hey this student service is relating to this class right over here well it's going to know once i define the type of this variable right over here and the type of this variable is going to be well student service so if i go ahead and i define the type of it if i say student service and notice how it auto imports it actually knows that i'm basically using this class right over here so now what i could actually do is i can do something like this dot student service and then dot get student and it actually knows about it which is terrific this is great and the reason why it knows about it is because i actually injected it inside of the provider and that's the only reason why it knows about it because really here we're just defining a type it doesn't really define everything that's inside it but it knows about it because we injected it inside of the provider okay terrific and so one thing that we actually have to do now and we actually unfortunately won't be able to test this because typescript is we're gonna have to fix all the typescript errors beforehand but one thing that we also have to do is we we should probably define ultimately the type that we're going to be returning and this is going to be the exact same type that we defined over here so we can basically do that and let's just auto import it in and there we go cool all right so that is the get students now let's actually go ahead and let's do the same thing for the get student by id and then get the post and then get the uh uh get the uh or sorry update the student so this might uh this might be a little bit tedious but hopefully this kind of makes a little bit more sense so to do this we're going to have to create another service and what's great now is because we have created a service that extracts all the logic our controller is just responsible for getting the request and sending back a response and right now it might seem like okay well we could have done that exact same line but for the more complicated ones trust me you can see how it actually separates the concerns a lot better okay so let's begin with get student by id so get student by id and what this is going to do is it's going to take in the student id or you know what we'll just call this we'll call a student id so this is going to be student id and this is a string and ultimately what it's going to return this is going to return just one student so we can basically do something like this dot students dot find and we can basically say that hey we want to return student dot id triple equals student id all right so that's really all we're doing let's actually define the type of this as well so let's go here and let's define the type of this as one student okay cool cool cool so now what we can basically do is we can just go here and then we can just say this dot student service and then we can do get student by id and we can pass in that student id to that param okay cool so that fixes that so now let's do the create student so let's go here let's create the create student service and so now in here we're going to basically have the body and we're going to call this the payload for us and so remember this is going to be the body ultimately of the of the student itself now this let's actually define the type of this is going to be called the create student dto notice i also auto imported it and it's going to return well the student response so it's going to return the student response dtf and for some reason did it auto import okay no the reason why it's failing is because well we're not returning that right now we're actually just returning undefined okay cool so now ultimately what we want to do is we want to create that student and push it into our database so let's actually do new student so new student is equal to an object and the new student is going to have an id that we're going to automatically generate as well as the name and the teacher id that is inside of this payload so one thing that we could do is we could just destructure out this payload but we do still have to manufacture the id somehow some way so we still have to do that now i like to do that through a library called uuid so i can just do a quick npm install uuid and it's just going to create a bunch of uuids for us okay so now what we can do is we can just import from uuid and we can basically import i'm going to import a specific hash function or whatever this thing is that creates a uuid called v4 i'm going to say that hey as uuid so i can just call it uuid so now what it can basically say is call uuid to just generate a random uuid all right so this is the new student but now ultimately what we want to do is we want to push it into this uh this right over here into our database uh so we're gonna do this dot students dot push and we're gonna push in the new student so we're gonna push in the new student and then ultimately we're going to return the new student okay cool cool so now inside of the controller what we're going to do is we're going to get rid of this and we're simply just going to call this dot student service dot create student and we're going to pass in the body that's it so again look how simple the controllers are they're really really simple all right last thing is update the student so this one's going to be a little bit trickier so let's actually go ahead and do that right now so we're going to call this update student and this is going to take in a payload of update student dto and then we're also going to take in a student id that is a string this is in the params itself all right so this one's a little bit more complicated so let's actually uh uh let's define this right here so ultimately what we're going to want to do is we're going to return the updated student so we're going to return the updated students let's actually just declare that and let's just say this is of type student response so student response dto because that's ultimately what we're going to return and now let's actually do a uh let's actually get the updated student list so we're i know we're only updating one but we're ultimately going to want to update uh that one inside of our database so what we can do is we can just basically update that one and then get all of the others inside of an array so we can basically say updated student list and that is going to be equal to this dot students dot map because this is going to create the function for or the array for us however and then we can modify certain things if we want to we can basically say student i hate these big things let's just come up there we go so now we can basically say here we can basically do the check we can basically just say if student dot id is equal to id and the id is passed in over here as the uh student id so we can basically say that then what we can return or what we can do is we can basically say that hey the updated student is equal to so the updated student is equal to the the student id so the id is still going to be the student id and the uh and then and then but the uh the name and the teacher is going to be determined by the payload so the name and the the teacher is going to be determined by the payload and then over here we're just going to do else and then we're just going to return the student itself because we don't want to manipulate that particular student so now what we can do is just simply say this dot students is equal to updated students and so that's going to return a list of all of the students and and the updated one as well now this is failing for some reason so oh no updated student list not updated student this is why i love typescript there we go okay so now we're going to return the updated student so we're going to return that updated student cool so now if i go back to the student controller very very simply what i could do is just do this dot update student and then we're going to or sorry this dot student service dot update student and then we're going to pass in the body then we're also going to pass in the the student id cool so that's pretty much it so that right there is the service so let's actually go ahead and let's do this for the teachers as well so the teachers very very simple so let's actually create another service so we're going to do uh uh nest and then we're going to new nest generate and then we're going to generate a service for the teacher we're going to specify the no spec flag so let's do that right now and let's wait there we go so now inside of the inside of the teacher we should have a service as well so let's go about creating this service and notice it's exactly the same we have the injectable decorator which is pretty cool okay so in here let's actually just quickly get rid of some of these other services or some of these other files let's open this up so we want to get the teachers let's have a get teacher so we're going to have a get teacher service and in here what we're going to do is we're just going to simply return all the teachers so let's actually put the variable over here so uh private teachers is equal to teachers from our database let's actually extract this out a little bit properly from our database cool and so now what we can basically simply do for this one is just return this dot teachers and then let's define the type as well so find teacher dto and this is going to be an array entry of that okay cool cool so that is that let's just create the other service as well so get teacher by id and then this is going to be teacher id and then string and this is going to return find teacher dto and then we're just going to return this dot teachers dot find and then we're going to do teacher and then ultimately we're just gonna do teacher dot id is equal to teacher id so teacher.id is equal to teacher id that's that's pretty much all that we're doing okay cool so now well again to use this service we actually have to tell our root component or root module about it so we can just say teacher teacher service or yeah service and then in here we can basically inject that inside of our constructor so we can say private read only and then we can say teacher service and then ultimately we can basically import in teacher service notice again we auto imported it so now what we can do is we can do this dot teacher service dot get teacher call it we're done and then similarly over here we can do this dot teacher service dot get teacher by id call it pass in the parameter which is the teacher id and then we're completely done all right so the absolute absolute last thing that we have to do is we have to create the uh the uh essentially the service for the students as well now in inside of these inside of the student controller inside of the teacher director now this right here we can actually just use the student service that we created inside of the student directory so we actually don't have to create another service we can actually use this same service because again this service is just handling anything really student related so we could just use this exact same service which is pretty cool and so in here we're going to actually have to have the uh uh the the logic that allows us to um uh oh sorry so over yeah and here we're gonna have the logic that allows us to basically uh create these two routes as well so let's go about doing that right now let's begin with the first route that allows us to inside of the controller get students but all students that belong to a specific teacher so in here let's actually create that service all the way down here and so this service is going to be called let's see what we're going to call this we're going to say get students so we're going to do get students by teacher id and so here we're going to take in the teacher id which is a string and ultimately we're going to return the find uh find teacher response dto which is an array entry so all the students and so here what we're going to do is we're just going to do return this dot students and we're going to filter out all of the students that don't have the id that we've specified here so we're going to filter by all the students that have this id so we're going to say student dot teacher because remember the teacher is the uuid so let's just quickly illustrate how the data looks like so all students have a teacher that has an id so you can see here all of the students have a teacher that have an id and basically what i'm going to do is if if i want to get all the students for miss jackson i'm basically going to go ahead and just filter for all the students that have this exact same uuid so miss jackson has anthony cole michael bryant kobe jordan and i think mr wade has the other two okay so that's basically all this is doing this is a relatively easy one so let's actually go ahead and let's use this now to use it again we have to inject it inside of our constructor so let's inject that into our constructors we're going to say private read only then we're going to say student service and then we're going to call this student service and let's just fix the imports i hate when it does this so inside here inside right here cool all right so now what we can basically do is again get rid of this and just use this dot student service dot we're gonna get student by teacher id we're going to pass in the teacher id and it's not happy for some reason let's actually hover over it so it says that find is not type find is not assignable oh okay all right so this is fine student but over here i said find teacher okay cool cool apologies for that there we go now the type is good all right the last service that we need to create is one that updates the student so let's actually create that right over here so the last one is we're going to call this update student teacher and this is going to be the it's going to take in the teacher id which is a string as well as the student id which is also a string ultimately it's going to send back that that student that we ultimately ultimately updated so that's just one student so we can just say student response dto and then over here we're really just going to have very very similar logic to what we did when we first updated the updated our student so let's just copy this and let's just paste it in here and we'll just do a little bit of changing so this is still going to be the same and then over here we're still going to map through everything and we're going to check if the student id is equal to the student id that was provided in the parameter now the only difference here is that the student is ultimately going to stay the same their id and their name is going to stay the same we're not going to update that we're only updating the teacher and we're going to update the teacher to the teacher id that we provided and the parameter so that's ultimately really what we're doing other than that it's exactly the same so now what we can do is well let's get rid of this now what we can do is we can basically save this again go over here and then just do this dot student service and then we can basically update our student teacher and again we would have to provide the we would have to provide the teacher as well as the student id now just let me quickly remind myself first we want the teacher id because of course the parameter order matters and then that's it okay so now if we go back over here everything is working fine which is great because all the typing errors are are fixed so let's actually test this out in postman where do i have postman okay so it says selling postman getting all the students it gets all of the students cool so that works get student by id so now we're providing a specific id and it seems like that works so now we get cole anthony let's create a student so now we're creating this student with this teacher so we get back that student i know if i do get all students notice that okay the last student is kendrick jenner you can see here that we got ben andrew which is the last one let's also update a student so we're updating a student's name or update student info so here is the student id that we're ultimately updating and this is going to relate to this this first student cole anthony and we're updating their name to heather andrews for some reason so you can see here that we get back this response now if i were to get all the students for some odd reason this is null huh that is pretty strange actually [Music] why is that i'm actually a little flustered i'll have to uh see exactly it's probably something wrong with our uh logic uh but uh yeah for some reason this is this is ultimately returning null it's probably something wrong with our logic uh it's probably actually something to do with the uh the the mapping so um let's actually go try to fix it right now if not i'll pause the video and fix it later uh so let's go to the student service and ultimately here okay cool yeah because we're not returning um so we're basically declaring it but we're not we're not returning anything so what we have to do is just return the student the updated student and actually i actually also didn't do that here so we would get the same exact error so you actually have to return it that's why it's null so if i were to let's do this again now i almost forget where i leave postman so again so let's just get this off so now we got cole anthony if i were to update that and then go back over here you can see here that uh heather andrews is fine okay cool so good thing i didn't have to pause the video get old teachers we get all of our teachers get teachers by specific id passing the id in the param okay cool so that works all right so now we want to get teachers uh so get all the teachers that belong to a specific student so this is getting all the teachers that belong to um i'm not sure which which uh teacher this is but it has definitely has a lot of students so let's just quickly check here that this logic works so we have one two three four five five students do we also have five students here one two three four five so it seems like all the students are associated to that particular teacher i'm not sure if that's the way that i architected it or not but it's fine for now and then we can also update a particular student to a particular teacher as well so if i were to get all the students for that i'm not really sure actually if if this logic is working properly or not so let's uh let's actually update so let's just figure out exactly actually no the the the teacher ids are different um so i should get all of the teacher ids for uh for this one i shouldn't get i shouldn't be getting uh kendrick jenner so the logic for this is actually flawed and it's not working so let's let's try to fix that right now so what it's doing is it's it's returning that's so funny okay so we're just returning um we're just returning we're we're not really doing any checks here so what we have to do is you have to return teacher.student.teacher is equal to the teacher id that's that's what we have to do and that's why we weren't getting any of the um any of the uh conditions so now if i were to send this request off you can see we actually get three because only three students are associated to that teacher okay cool so we learned about services i know this was a very long one uh but in the next section we're actually going to start working on a way to actually validate our our requests and validate basically if the data that we're getting back is is valid and we're actually going to do that through pipes and middleware so stay with me because we're going to learn about these in the next section let's explore a new concept in nest known as pipes and pipes are a way of validating data and transforming data let me show you what i mean by going to the nest documentation so it says here that a pipe is a class annotated with the at injectable decorator okay that's fine let's start just talking about exactly what the use cases for pipes are so there's two typical use cases we have transformation and so transfer transforms the input data to the desired form so we can transform it from a string to an integer and this could be very very desirable especially if we're using some sort of sql database that stores the id as a number so let me just kind of quickly illustrate this right now we're using a uuid which is a string but let's say we were using some sort of sql database that was basically storing the id as a number however if you know basic javascript or basic express the param will always be returned as a string so what we actually can do is just transform this string into a number automatically without us doing any parse into any parse float through pipes and i'll show you exactly how to do that in this example another thing that we can do and which we will do in our section is validation so essentially we can val validate the input data and if it passes then okay we go through however if it fails then we throw an exception and this is actually what we're going to be doing in our example and there's actually a built in type or built in pipe rather that will validate whether the param itself is a valid uuid so uuids have a structure that they have to have in order to be well uuids so there's actually valid uuid forms and then forms that are not even uuids and to kind of illustrate this we can just go to uuid validator and we can paste in that uuid that we had well this is a valid uuid however if i remove this 3 and thus decrease the length of this uuid you can see that this is not a valid uuid now if i put a four okay that's the value uid what if i decrease this and then i increase that well that's not a valid uuid a uuid has a structure imposed like a very strict structure and what we can do is validate if the param is a actual valid uuid because if it's not a valid uuid then no user is going to be associated with that uuid unless there's no point of continuing on and so we can actually use a pipe to quite easily accomplish this now in in a nest there's a few a few built-in pipes we got the validation pipe we have the parse int pipe we have parse boolean pipe parse array pipe and then we have the parse uid pipe which this is one this is the one that we're ultimately going to be using and then there's some other pipes let me just kind of quickly illustrate how we use the parse int pipe to actually transform a input from a string to a number let me just quickly illustrate that and then we'll go ahead and use the parse uuid pipe so inside of here inside of the parameters we have the at param and then the id now this id is going to be different than our id it's probably just going to be some sort of number rather than a uuid and so what we want to ultimately do is parse it into a string or sorry person into a number well automatically it's going to be a string but if we actually pass the parse int pipe it's going to automatically parse it to a number so you can see here that this is of type number and okay now if you call something like this obviously this is not a number so what it will do ultimately is actually throw an error response and this is great this is actually what we want we want to throw an error response if we get something like this if we will have numbers so this is one thing that we can do we can also handle the uh the responses any way that we want we can basically error http status code and we can give our information that we desired and that's basically how pipes work they're really really easy now we are going to use the uuid pipe and this uid pipe is simply just going to check if this is a valid uuid if it's not a valid uuid it's just going to go ahead and throw an error throw an exception and you know this this actually works with all the other pipes as well so in the documentation you can see here uh yeah so i'm not sure exactly where in the documentation it says it but the other pipes work in a very very similar way so you can basically kind of use this old parse array pipe to ensure that hey you're actually getting back an array or parse a bool pipe to ensure that you're getting back a boolean okay that is awesome awesome possum so let's actually go ahead and use this pipe right now this is going to be a very very easy and quick section let's actually remove this dto seems like we're not using it and what i'm going to do is i'm just going to close everything off and i'm going to start of course as i usually do with these students the student controllers okay so we are going to be using the parse uuid pipe and we're going to be using that in order to validate the params so we're going to validate this param over here because this should be a valid uid as well as this one okay cool so how do we do that well from here from the at nest gs common we can just say parse parse uuid pipe and very very easily all we have to do is just pass this as a second parameter so we're going to call new parse uuid pipe because remember this is a class and that's it that's literally all we have to do and let's actually just test this out right now okay so let's go back to our code now this should be fine we should be able to get that particular user cole anthony now if i were to provide an invalid uh uuid so let's decrease the length of it by one now we're to pass this you can see here that i actually get an exception and the exception is validation failed uuid is expected which is great this is this is definitely what we want all right so let's just quickly do the rest this is going to be very very easy it's just going to be a bunch of copying and pasting so this section is going to be very quick over here we can do that as well if we have anything that we want to pass in here we can do that as well but we'd have to extract the extract the the body uh but there's nothing really in the body i guess maybe other than the the the teacher id uh so we we could do that but that's uh it might get a little ridiculous so let's not do that uh so let's go here and let's validate the student so over here let's get rid of this put seems like we're not using it so let's do parse uh we're parsing the uuid pipe again all we really have to do now is just call it very very easy just call it and we are done so we're done with this last but not least we are need we need to do it here so new uh parse uuid pipe notice that it probably auto imported and it did terrific let's call that and then let's just copy this and let's just paste that in there and let's paste that in there okay done and dusted so now let's just quickly give this a quick test so again invalid let's get rid of that invalid gives us an exception uh if i provide an invalid uuid here should also throw an exception awesome if i go to get teacher by id will it throw an exception yup absolutely terrific uh get teacher to do so so if i have an invalid teacher throws an exception if i and then for the last one over here if this is invalid then throw an exception if it's valid of course it's going to work and then if i change this student we get an exception that's terrific that's uh that's really great and um let's just close all these off and that's ultimately what we want we want this this kind of quick and easy error handling all right so that's pretty much it for this section in the next section we're going to be talking about modules in this section we are going to be exploring the modules and we've already seen modules through the app.module i keep referring to this as the root of the application and we end up using this app module inside of this main.ts which basically bootstraps our nest application but what exactly are modules if i go over here modules are a way to really organize our components and a nest application will at least have one module and that is the root module and that's basically kind of the source of truth that takes all of the code that we want inside of our nest application and it basically displays that and creates our nest application through that but it is actually really important and highly recommended to create multiple modules for each component of your application to truly organize your architecture so what we're going to be doing is we're going to create a module for the student as well as the teacher and you might not really know what modules do but i'll try to explain them as well as i can by essentially coding them out for you so let's begin with the student so what we could potentially do is just simply go to our nest cli and just do nest generate and this time we want to generate a module and this is going to be the student module so let us wait a lot a little bit actually this might not even be a nest command i'm not sure why it's hanging oh it it created okay there we go okay cool so there we go we have generated our module and you can see that our module is decorated with the at module decorator right over here and then we have just a simple class and and this is just typically how nest components are built through classes all right so now that we have our module what we're going to do is we're going to start exploring the app dot app.module.ts you can see here that we have something called imports that we're not really using we will actually in a bit but then we're specifying all of the controllers of the application as well as all of the providers well let's actually do that for the student.module.ts and here we're not going to just specify every single controller in the application as well as every single provider in the application we want to really separate and organize our components so in the student.module.ts we will only specify the controllers and services that are essentially being used by this inside of this student directory so this controller as well as the service so let's go ahead and do that right now so we would do that inside of this object that was already kind of pre-built for us and you can see we can specify the controllers so here we can specify that we have a student service or sorry this is sorry this should be a student controller and then for our providers and i should have a comment here that's why it's not auto completing for our providers this is also going to be an array and over here we're going to have the student so we're going to have the student service okay and that's great that's pretty much all we have to do now let's create a provider or a module rather for the teacher so nest g teacher and then uh well nest generates and we want to generate a module and we want to generate a teacher module so we can put that in there should i don't know why it's taking so long uh these days but uh in maybe hopefully in like 10 seconds it's going to generate it and it did cool okay so now in here we're going to create our teacher module and so what we're going to be doing is creating the controller and this is only going to have the controllers that we have specified here note that we actually have two controllers so we're going to be using the teacher teacher controller as well as the student teacher controller so we have two controllers here as well as one provider which is just a teacher service teacher service okay cool so now what we can do and this is why it's this is really important we're basically defining all of the controllers and all of the services that are associated to that particular component but now what we can do instead of defining every single controller inside of our inside of our app.module.ts as well as every single provider what we can do is simply get rid of all this and just import the two modules into our app.module.ts that's really all we have to do is we can actually get rid of all this and what it's going to do is it's also going to start using the controllers as well as the so it's going to use the controls as well as the services automatically because those those modules are using those controllers and those services so over here we can just say teacher module and then we can also say student student module all right pretty much it really really easy so now if i were to save this let's go ahead and let us i just want to see where i'm running my application i think it's over here and you can see we're getting an exception and i was actually expecting this exception and this exception is basically saying that hey um this student service it's not really known in the teacher module we don't know about this in the teacher module and that makes sense because before what we were doing is we're exporting all we're basically defining all of the providers inside of the root module but now we're not now what we actually have to do is define the provider inside of well the teacher module as well so we actually have to define the student service in here now one thing that we can do instead actually is go to the student controller or student module.ts that contains the student service and what we can do is we can export we can export that student service because hey that student service is needed so that student service is really important all right so that still doesn't tackle the problem that hey the the teacher module requires the the student service and if you don't remember why it requires a student service is because of this right over here in the student.control.ts inside of the teacher module where we're basically using that student service right over here so now what we can do is we can say okay well here what we want to do is we want to import the student module so we import the student module which automatically exports the service and you can see here that everything is fine and you can see that inside of our app.ts all we really have to do is import the modules obviously as our application get bigger and bigger so will this uh so will this array but it's actually better than putting all of the services as well as all of the uh all of the providers which will make this component huge and so this is a really good way of separating out our concerns and just to double check everything is business as usual everything still works cool in this last section we are going to cover how we can use middleware inside of a nest js application now middleware is not a unique concept to nest js it is used throughout every single backend application regardless of the language regardless of the framework it is very very common practice to utilize middleware and that's why it's so important to learn how to utilize middleware inside of a nest js application and to kind of quickly explain exactly what middleware are i have this nice little diagram so typically what we would do is we would make a request the client would make a request and in our nest application it would go to the controller or our route so the request would go to the controller the controller would then call the provider which is the service and then it would send back the response to the client not back to the request itself it would actually send it back to the client so i hope i hope that makes sense now if we add a middleware it kind of acts as a middleman so what happens is the client makes a request and then the request doesn't go straight to the route it actually goes to the middleware and then the middleware does have some sort of information has some sort of it processes that request and if everything is fine and dandy then it goes to the route or the controller in this case and then the controller obviously does the business logic and then ultimately sends off the response back to the client and so why do we need this middleman well we need this middleman when we have a lot of repetitive code for instance let's say we had a lot of repetitive code that we used throughout every single route let's say we had five routes and we had a lot of repetitive code let's say for instance we were validating if the uuid actually belonged to a particular user so not if the uuid itself is valid but what we what we wanted to do is we'll validate if the uuid even belonged to a particular user and if they didn't then just don't even pass it to the controller just don't even continue well we would do that through middleware and then we can basically apply this middleware through every single route that we want it to be applied for another reason why we would want to use middleware is maybe we want to make sure that hey the client is actually authorized to make this request so again we can make a request but maybe we're not authorized to make that request maybe we're not logged in or maybe we are logged in but we don't have like premium access so we can't make that particular request well we can have a middleware that basically checks that for us another way we can have a middleware is uh you know other error handling kind of related things and also the middleware can sanitize our data and actually inject data inside of the request so that the controller can easily use it for instance if we are basically trying to log in through a json web token for instance the middleware can basically parse that json web token figure out what the user is and then put that user data inside of the request and that way now the controller doesn't even have to parse that json web token it can just take that user data from the request and that's why middleware is really really important now in sjs middleware are very very very easy to implement so you can see here middleware is just a class it's just a class that we're going to create and then what we're going to do is we're going to inject that class inside of a module so we're going to inject that class inside of a module and you can read through the documentation if you want to but i'm just going to go ahead and do it and so hopefully that just kind of clears up any sort of confusion and hopefully maybe you won't even have to read the documentation even though i highly always recommend reading the documentation because they never cover everything in the documentation all right to create middleware what we're going to do is we're going to create a directory and i like to call this directory common this is where i like to put a lot of my uh common things that i'm ultimately going to be using throughout my application now inside of here i'm going to create another directory called middleware so i'm going to create another directory called middleware and then inside of the middleware i am going to create a valid student dot middleware dot ts and essentially what this middleware is going to do is it's going to get that uuid and basically check hey does this uuid actually belong to a particular student if they don't then don't bother sending the request to the controller so that that's basically what this is going to do but you can have multiple different middlewares again you can use middleware for authentication even though in sjs it's actually better to use guards for authorization as well as authentication but uh or actually i think it's just authorization that it specifies here so this is often referred to author authorization is traditionally handled with middleware and request but it's actually kind of better to do it with guards however we won't be covering guards because they're not that common in an sjs application so we're just going to be doing middleware all right so let's create our first middleware now remember a middleware is just a class just a class and so we're going to be creating a class and we're going to be uh to create this class what we're going to be doing is using the uh we're gonna basically be decorating it with injectable so we're gonna do at import and this is going to be from at the nest common and then we're gonna mark this with injectables we're going to get this injectable okay and so this is going to be the class so let's go ahead and just export this class we're going to call this valid student middleware so valid student middleware and then what we're going to do is we're going to do at injectable and so we're going to mark it with injectable all right and you can read about the documentation to learn more about injectable but this is needed to mark this as a middleware okay cool so now what we're gonna do is to truly mark it as a middleware because the injectable can be used for services as well what we're gonna have to do is we're going to have to essentially use another and not really a decorator but another variable here called nest middleware and then in this class we would say valid student middleware and then implements nest middleware and that truly defines it as a middleware now you can see that it's failing right now and that's because hey this class is not configured properly properly and that's because middleware always needs to have a use a use method so a use method and inside of this use method we are going to have the request and we can actually annotate that this is a request by importing it from express so we can import the type request from express and remember even though we didn't install express directly nest is built on top of express so it's gonna have it so express we can get the response as well we can get the next function so if you don't know what the next function is i'll i'll kind of inform you in a bit so we have our rec we're also going to have our response and then we're going to have our next function so next function all right so here we have the use now in here we're just going to have our logic we're just going to have our simple logic so if the user is actually valid and uh and that you that id actually corresponds to an actual user uh then what we're gonna do is we're going to say the take what we want you to do is move on where are we here move on to the next thing and the next thing for us is going to be the controller also the next thing for us could be another middleware but for here it's going to be a controller and that's where we're going to use the next function but if everything is not okay if that uuid doesn't correspond to an actual user then what we want to do is we want to throw an error okay so let's let's try this out so let's say const student id and we're going to get the student id from the rec dot params dot student id so we're going to get that student id from the rectal params because we're going to use this middleware with any request that basically has the student id in its parameters and then what we're going to do is let's actually go ahead and let's just import the data from our database so basically the student data we would probably use some sort of orm if we were you know using an actual database but for us we're just going to import students from let's see here where is the what directory is it right here from database we're just going to import students and what we're going to do is we're going to find if a student actually exists inside of this database with a student id of this that was inside of the wrecked op param so what we can basically do here is we can do something like const student exists and then we can do students we can parse through the students and then instead of using map or something like that we can use something like sum and the sum method basically what it does is it returns true or false it returns a boolean and it will return true if any one of the students that we've iterated over past a certain condition that we specify only one have to pass that condition for it to return true however if none of them pass the condition it returns false so that's what the sum method is doing and so the condition is basically going to be student dot id is equal to student id that's that's literally the condition and so now what we're going to say is hey if the student doesn't exist so we're going to say student exists but then we're going to say not so not student thinks this what we're going to do is we're going to just throw the error now how do we throw an error in nest well we do this through the http exception so http exception so http exception what this is going to do is it's going to throw an error for us we can basically throw new http exception we can specify a method so student not found and then we can say that hey this is a 400 error now if we pass this if we pass this if we so if we don't call this if statement then what we're going to do ultimately is call the next function and the next function is going to go ahead and move on to the controller and so that's basic middleware now how do we use the middleware for uh the the routes that we want for instance we're going to want to use this middleware for this and for this as well as for the other ones like we could use it for put as well for sure because that's also part of the param uh for now i'm just going to inject it for these two right over here just for simplicity's sake now how do we do that well we go to the module that's basically housing the controllers that are associated to these things so that would be the student module and then in here very simply what we do is we start manipulating the class itself so what we actually do here is we also do we say class student module and then what we're going to do is we're going to say that hey this implements so this implements nest module nest module notice that it auto imported nest module in here and basically what this is going to do is it's going to allow us to add additional configuration to the student module and so we can actually specify the configuration with the configure method so the configure method so without this nest module we wouldn't have been able to do it it doesn't really throw an error but again with this implement nest module we can actually go ahead and configure our student module the way that we want it and so now we can basically say hey we want to use this middleware now how do we say that hey we want to want you to use this middleware we can do that through something known as a consumer so we can basically say consumer and essentially this consumer is going to be passed into this configure and this consumer is going to be of a special type and this consumer is going to be of type middleware consumer middleware consumer notice again how it auto imported right over here and so now what we can say is that hey we want to basically use this consumer consumer dot apply and then we want to apply the middleware that we just created valid student middleware again auto import it i don't like how it auto imported it so i'm just gonna import this one myself so this is in the common directory slash middleware slash valid student middleware so we're gonna basically consume this middleware but for which routes are we going to consume them for well we want to consume them for these two routes over here so we would just say four routes or four routes and then basically here we would specify the path of the route that we want this middleware to be consumed for so here we would say students and then colon student id and then we would specify the method so the method because we could have a post request with this exact same thing or we could have a get request we have to specify the method to specify the method we do request method again auto import it from here and then we just do dot whatever the method is so this is going to be the get method now so this handles this one right over here however we also want to handle the put request this is a kind of a perfect example showing you that hey we could have two of the exact same routes but the methods could be different so what we can do now is just literally copy and paste this and just paste it in again but instead this time we have a put cool all right so this is awesome so what i'm gonna do actually is i'm gonna quickly over here just console.log that this middleware was called hey this middleware was called so let's quickly save that let's open up our terminal and let's make a request to one of these two routes or yeah one of these two routes over here let's start off with the uh slash student slash or colon student id get so let's go here and if we make this request everything is fine however if i actually go back you can see this middleware was called but because everything was fine the next function was called and it went to the controller now let's provide it with a a student id that doesn't actually belong inside of our database so let's just change this from three to four let's make this request we get an error so now we have a status 400 error saying that students have not been found and that's great that's pretty much how middleware is is used so we can actually do the same thing over here and make that request again yeah and and that's basically we can basically modify this middleware for however kind of functionality we want if you want to authorize users we can use the middleware if you want to authenticate users we can use the middleware the the real point is just knowing how to use a middleware in a nest application so that pretty much ends it for me i hope you guys enjoyed and i'll see you guys in the next one
Info
Channel: Laith Harb
Views: 20,167
Rating: 4.961844 out of 5
Keywords:
Id: S0R82Osg-Mk
Channel Id: undefined
Length: 135min 41sec (8141 seconds)
Published: Wed May 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.