Nestjs Full Course 2022 | Beginner Nestjs Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to this nest js amazing course where we will talk about not just how to get started with nest js but we will connect with mysql database we will understand the core component of nest js and we will also do the authentication with the passport package and the jwt to create the token everything in this episode but let's first see exactly what we are going to learn so in this course we will first start with what is nest js because we need to understand what this is and then we will create a first new project all these course is a mixture of hands-on training and some amazing slides with animations so you will get each and everything very easily after that we will talk about the features of nsgs why this is so popular and why you should use it then we will explore the directory structure of ness js after that we will move to the nest module the three main component of nest js is controller module and provider so first we will see the module after that we will talk about the controller and then we will create our own controller and we will see how we can create our own controller then we will see what is nest cli and how it is useful in your development process it is really really amazing thing you should try it out now after that we will also talk about the service providers as i told you three main component controller module and provider so here's the provider after that we will see what is dependency injection in general in general in programming and how that dependency injection is useful inside this nest js then we will see the payload how we can fetch the payload when we send some data through a post request or patch request then what is validation and pipes inside the nest js and how we can connect with the mysql database this is really really important topic and you should focus on this one after that we will see how we can do all the query inside our mysql using the type orm and do all the crud and after that the most important topic of any framework web framework is the authentication we will see how we can do a normal authentication and then we will use the passport package to do all the authentication but when user is logged in we need a token so we will use the jwt package to create a jwt token and after that we will use that token to pass the token inside the bearer inside the header for authentication as a bearer token and then we will create a protected route and finally we will able to access that protected route only with the token if no token no access so everything is in this course is just for you and if you like this video please hit thumbs up and subscribe to bitfumes youtube channel it's very important to support me with your thumbs up and subscription and if you have any comment related to nesgus or if you have any requests for any other thing comment below because comment section i always check every time i open my youtube i just go to the comment section and check what you have written on that so one thumbs up one subscription and one comment is mandatory for uh for a thanks for this kind of video if you like it okay so enough talking let's start this course [Music] nest chairs is an amazing framework it's a progressive node.js framework for building efficient reliable and scalable server side application and this course is going to take you from starting from what is next js to creating a nice little application and with nesgus don't get confused with next gs because next gs is a front-end react framework while nest js is a node framework to build server-side backend applications so let's start with our first topic what is nest js now as we know ness js is for building efficient scalable node.js server side application it is progressive javascript is built with fully support of typescript this means the node.js which is a really powerful thing type script which is another powerful thing and when these two power combined there is a blast and that blast is called nest js it combine elements of object oriented programming functional programming and functional reactive programming so all the core principles and the rules and the basics of programming are already inbuilt inside of this nest js framework under the hood nest gs make use of robust http server frameworks like express.js which is the default one and if you want to use fastify then you can switch from express js to fastify so this express which is nowadays a synonym for node.js is really really really powerful node.js framework and over that this nest js is build but why why we need another framework over a framework express js never tell you how to organize your application so when your application become bigger you will feel like how to organize things are getting complicated directory structure is not good and the new team members will feel like what is this but with the nest js everything is organized everything is properly suggested like where you put the controllers where you put the routing where is the service and everything is up to the place and that's why we need a framework called nest js over another framework called express now nest is is using express it doesn't mean that nesgus says that only my api will going to work no if you are familiar with express.js then it's all up to you if you really want to use express core api if you know any package which is working with expressjs yes you can use that with nasjs also with all these things now it's time to get started with nextgs and installing sgs in our system to get started with the nest js we need to go to the nestgs.com a simple website which is having a very nice red button called documentation just click on this one and you will land to this page yep it's an introduction and some of the things but we are interested in the installation part so the very first thing you need to do is you need to have a global installation through npm for the nest jscli cli stands for command line interface that means a command line or terminal thing you can do with the nest js so let's have this in our system so i have opened the terminal if you are on windows you can open the command prompt and here we are this is going to install this nest js cli globally in my system this means it doesn't matter where i am i can just say n e s t and here you can see we have a list of commands which we can use with this nest command line so what we can do we can first say new which is to generate nest application it's a very nice to have new but we have a short form which is n so if you just say nest n and after that the name of the application it's going to create a new fresh nest application in your system wherever you are running this command we have other options also we will explore them later but first let's create the new project so i will have this nest js directory where i am inside this nest js directory so i'm just going to say here like n e s t then i can say new but i want to use the short form which is n for the new and i will say my app this is the name i have given you can name it anything when you hit enter first it says we will scaffold your application in few second it has created some of the things but at last it says that which package manager you want to use now what is the package manager package manager is a manager or something think about this as something which can install any javascript library or uninstall any javascript library in your uh project so we have npm we have a yarn or we have a pnpm so i'm familiar with npm you can use anything it totally doesn't matter so let's hit enter and then it says installation in progress so it's doing the npm installation once this is done we will be able to use our nest js application and we will open that with our vs code now finally our application is here the project is created and we can just cd into my app and then we can start but before that i just want to open so first let's go inside this and then i say code dot that means open this project with vs code here i am and here is the full directory structure you can see git ignore is there that means the git is initialized and all these things are there that means if i can open the terminal and by the way i have the shortcut for this you can open terminals from here new terminal like this so what you can do here you can say git status and it says that hey all these things are not yet committed so i will say get uh first add all and it has added to the the staging then i say you can see staged all these things and then i can say git commit with a message of my first nest app okay so it has done with all these things don't worry about that password thing it it's not for you it's just for my system okay so everything is now clean and here we are but what else we need to do once we have created the application we need to run this command npm run start so i say npm run start while this is doing our magic let's open the package.json and here you can see we have scripts we can run and the script we have just ran is this start which is a nest start by the way we know that we already have this nest cli command line interface so can we use directly this thing obviously yes so you can see we have this running it's on the localhost 3000 so i can open localhost 3000 and you can see we have this hello world printed here where is that i need to zoom out it's too zoomed yeah hello world is here okay so i can just press command and c to kill this server and i can now use nest start instead of npm run start both are exactly same so yes it is going to be exactly same and how do i know that ness start is there one is obviously from this package.json also if i can just run nest and we get all these things and we have this start command here which says that run nest application so this is all about starting and so easy how to get started with nesjs how to create the fresh fresh project for the next years before moving forward in nest js let's understand some of the great features of nest js framework and first i will say that nesjs was created to help developer create monolithic and microservices nesjs is created for developers and it makes developers life easy so that developer if they want to create monolithic or micro services they don't have to worry about these things because everything is possible with nesjs it's very simple to use quick to learn and easy to apply and that's why nsgs is so popular it leverages the type script which is a strongly typed language which is a subset of javascript now if you don't know about typescript i have a full tutorial of the type of script you can check out but films type of script videos and type a script just provide the typing in the javascript so you can define the number or string or you can define your own type and with that this nes js becomes extremely powerful it's having a powerful command line interface to boost the productivity and easy of development and we just saw that to create a really nice project we just need to say nest which is a command line interface nest new and the project name to start our application we just need to say nest start and later on we will explore amazing thing about this cli thing after that net js support dozens of nest specific module that help you to easily integrate with common technologies concepts like ora mongoose graphql logging validation caching websockets everything is there and this means it's a full package of web framework next year's not only just provide you ability to create any server side application it has also provide you the unit testing that means you write your test to ensure that any feature is not breaking when you go into the production and with a great documentation everything become easy and the power of any software any open source or i think i think any product is is limited or is not popular i can say when it doesn't have a good direction or documentation so an sds has a really great documentation which is taking you from each and every concept to the bigger concept very smoothly and this is the reason next year's become very easy to learn and finally it's a build for large scale application and it doesn't mean that you cannot create a small application you can create but it is built for large scale applications now we have this project and let's talk about the directory structure and the files we have but before that let's talk about the components the main components of nesjs so in nfcs there are three main components which is controllers providers and modules so we will talk about each of these three one by one but let's first see what we have in our project so starting with the package.json which has a lot of other scripts other than the start we have already seen so when you say start dev then you don't have to restart your server it will watch for any changes if you do in your project the debug is for debug mode produce prod is for creating the production ready application some of the linting so that styling and linting then we have a test test watch test coverage and all other test related things and after that we have some dependencies so nest js common which is very nice package we will use many things from this library then we have a core then platform express as i told you nfcs uses express as the default http server then we have some other things in this nest yes framework now after that we have the ts config ts config is the type script configuration we already know that nest yes has the power of node.js and the typescript and that's why we need this typescript configuration which is obviously related to typescript so we don't have to worry about it after that we have this nest cli dot json which is just having some like nest related next cli related information and this is actually saying that when you say something related to the next cli where it's going to produce the files so with the nest command you can create some of the files like you can create the application you can create the controllers providers so where it should create so here is the src directory which is this one so it will create the next cli will create the files inside this source directory okay then prettier then git ignore eslints are common thing then we have a test directory where we have the just configuration okay so it uses the jest framework for testing and this is a very little uh test a demo test it has given to understand how the testing works in nest cheers then we have this very amazing and the very important directory called src the source and any javascript project starts with either index.js or main.js so this nest starts with main dot js inside this main.js there is two things going on first you can see this is app listen 3000 if you are familiar with express.js you may have seen this kind of code which is to start the server or start the local server i can say which is extremely important and this is inside a function called bootstrap and finally we are calling this bootstrap function now other than this creating a server with a localhost 3000 we are doing another thing which is called nest factory create that's okay but we are passing this app module now remember we said that there are three main components in sgs controller provider and modules so we come up with this module thing so this app module is coming from app.module where is this this is on the same directory so app.module.ts is here so the job of this main.ts file is to load app module and start the server you can change your server settings or server port just by doing this and then if you say nest start i can do like this and it will start on localhost 3001 not on 3000. so if i reload it says offline but on the 3001 we have the hello world let's get back with the 3000 and close this main.ts because now we need to focus on app module okay let's open this app.module.ts every file is having extension of ts which is for typescript now we can see this file is just a simple class or an empty class if i remove each and everything you will see that this is just a normal class exported from here and here we are importing this that app module and passing it to nest factory so what makes this class as a module so let's undo and we have this decorator off at the rate module okay this is extremely important whenever you want to make any javascript class as a module you need to add this at the rate module now this module app module is having two important thing which is loading the app controller and app service now where is app controller and app service on the same directory you can see app controller and app service are here so let's close this app.module.ts and open app.controller now once again if i remove every other thing this app controller is just a normal class which is exported here and inside the app module we are importing this but to make this as a controller we need to use the decorator called controller and this makes this class as a controller for nest chess similar to this controller we also have this app.service.ts and once again if you see this if i remove everything this is yet another a simple class which is exported here and imported in app.module.ts cool but what makes it as a provider this injectable decorator and this is extremely important once again so we saw that to make things very easy nest js has very little decorators provided which makes or which add the metadata to the class and that metadata defines the purpose of that class if i use injectable then class become provider if i add module the class become module if i add the controller it the class become a controller and at the same time we also have appcontroller.expect.t which is a testing file for this controller that's really really cool but we have seen that if we go on localhost 3000 i can restart it like here so if we go to the local host 3000 we have this hello world but from where this hello world is coming for that we need to go inside the app controller and you can see we have this get at the rate get and we are not passing anything we have some class name we have some function name called get hello and then it says this dot service dot get hello and where is app service we know app service is here and inside this app service we are calling this get hello function so go here and you can see yes we have this get hello which is returning hello world now let's change it to hello bitfumes now it has changed but it has not detected the change remember we need to restart the server or we can simply say npm run start colon dev once we do this it is start watching any changes and now if i reload it has hello bitfumes and now i can do another change hello bitfumes nest js course now as soon as i save this file you can see it has detected the change and restarted the server quickly and now if i reload you can see all the changes are reflected here inside this browser so this is the way we can understand and we can see how this nest js is structured what are the classes we are doing and what is there now that we know what are these files are doing inside this source directory which is extremely important i'm going to do one amazing thing and what it is which is simply removing these three things app controller appcontroller.spec and app service so let's just move everything to trash cool now everything is removed we are just having main.ts and app.module.ts and i can just remove this one too and start with the very minimal thing now what we have we have nothing here so if i say next nest start you can see that it says that hey you don't have the module so i can just remove this thing and maybe i can just not pass this and say that hey you need to pass the app module so let's create the app module by our hand that means creating this manually so creating things manually is a great way to learn anything what that file includes so app.module.ts is the thing we need and we have the experience that everything is just a class exported so export class app module and since this is a class i just need to do something like this and provide the app module here and finally let's start the server next start and let's see what's going to happen when we run this application on localhost 3000 so if i go on localhost 3000 it says hey there is the error of 404 because it says that you don't have any route available for the slash or the base url so simply not found ignore this error this is just type descriptors not able to find it it will find it very soon but for now what happened is we have this app module but this app module is not a nest js module remember to make this as a nest js module we need to add the decorator of module and this should come from nest common this is extremely important nest js common so i have added this and then inside this we have to pass this empty object to make this as a module so this is now become a real module now i want to make this as a npm run start div so that whenever i do any changes it will detect and restart the server still we are not having it but let's go on the slides and understand about the module a bit more so modules in next years is very important part a module is a class annotated with module decorator which we already know each application has a root module so when i say root module that means i'm talking about the app.module.ts which is directly inside the source folder okay and that root module uses a starting point to resolve the application structure and risk relationships so why it resolve everything because we know in our main.ts we are actually creating the nest application using this app module which is this app module which is the root app module and that's why it is very important it is highly recommended to use multiple module to organize your application component now what is this multiple module now suppose i want to create a user related controller and services so i could create a user directory and inside that i can put user.module.ts and in this way we are actually creating multiple modules to organize our application component so suppose this user related things is a user component so we created user.module.ts something like that okay next the module decorator provide metadata that nest make use to organize a structure so this module a decorator is extremely important because here you can define some of the metadata metadata means the information about this class for the next js now and inside the nest gs we have the main application module which is a root module and each other modules will go inside this app module so in our app module we always need to register other modules here inside this app module so this app module will going to register other small other modules of our nest js application so as we already know i told you it can connect with other things so if we have a cat module which is just for the cat and in that way this cat module will going to connect the controller called cat controller then the providers called cat service so this is very very important concept in nesgus so yes we know how to create the modules but still we are having nothing on our base url if i go to localhost 3000 it's nothing not found so how we can create the route in our nest project we have removed everything but we have created manually app.module.ts when i say manually it's i'm saying again and again because you can also create these modules via the nest cli but we will talk about that later so even after doing this we don't have anything on our route or the base url so for that we need to work on the controller so let's first understand controller in nesjs now a controller purpose is to receive the specific request for an application so controller is controlling the request and the response okay now the controller then handle the request and return the appropriate response so it handle the request for a specific route and then return some response according to the code we have given then you can see from client side like any user when they hit or when they provide a http request to our next application that request will go to one of the controller from our application and then that controller will do its thing if that route matches to that controller routes we will see that later but a normal controller looks something like this in nest js i told you everything is just a normal javascript class exported so here we have a class which is exported called cats controller but over that we have a decorator called controller and that's it we don't need any more thing to make this class as a controller so let's jump to the code and see how we can create the controller once again manually and do our things let's go to the code and here i'm going to create app dot controller dot ts ts4 type script now i told you we need to create a class called app controller that's a simple thing and now to make this class as a controller i have to say a decorator of capital c controller and once again that will be coming from nest js common module and that's it so yeah we have a very nice controller now this has become the controller but is this going to create any route for us okay so let's see the server is running let's go and reload this page still nothing is there so what actually we need to do inside this controller we need to create a simple function which should return anything so i'm going to first write a function called get user okay and this is a very simple function which is going to return i am a user simple this is very nice but is this going to work you can see the changes are detected but if i reload still nothing so what happened is the controller is here but the nest framework doesn't know about this controller so how we can tell to the nest is that hey in fjs use this controller and here comes our app.module.ts here inside this app app.module.ts on this module decorator we need to give the information about the controller so first i can say hey the controllers it's going to be an array of controller so i will give that app controller is there and just by adding this we have solve our issue okay so now if i reload you can see i am a user is here and the best part of nest js is here i'm returning just a string but what if i want to return an object of user with the name of sarthak and then comes the email as sarthak at bitfumes.com okay so this is the simple object i'm returning and what will be the case when we hit the route see this it has converted it into very nice json object which is really needed from an api and this is the default system for nest js we have done nothing for that but it's very easy to to write these things and nest just will take care of everything but what if we really want to change the route it's not just the base url or localhost 3000 what if i want to say localhost 3000 slash user if i go there still it says not found because there is no controller handling that route so there are a couple of ways doing this so first you can create a new method and inside this method you can say let's use the same method and here inside inside this get decorator i'm going to say hey this is for slash user route this means now we lose the low close 3000 but we have locals 3000 slash user so you see it's here but when i go to localhost 3000 it's not there okay so this means whenever we have to create any route we have to define it here but it will be very difficult to create a route which is having a long list suppose we have a user then comes suppose the id of the user maybe i can write it like this then send and then comes the email and it's becoming very long so what we can do instead of giving user here we can say that hey this controller is for slash users and any route we create here will be prefixes with slash user so slash user and slash now if i say slash user comes the user id then it will become slash user slash user id something like this okay so let's try with the base one and we have defined the user here and if i go reload not working but if i go here on slash user yes it is working because now we have defined the base route on the controller okay so this is just for your information we will tackle these things later but just like the get we also have a post so when we talk about the post that means we are creating something that means we are storing the data into the database so now we can say a store method is there which is just going to return i am storing uh storing data into database okay that's it but this is for again the base route don't get confused this is base route with a get method this is base route with a post method now how do we check this one like the post because from the browser you cannot send any request so here i can easily do this but to to send a post request we need to use either insomnia or postmen so let's open the insomnia here we have ins in our system so insomnia is there and now i can just say localhost 3000 with a post request and now if i click on send you can see it says 201 created and amazing part of ness js is nest js know that if you are using post method that means you are returning some kind of created thing you are doing some create part and that's why it has return 201 created here inside of the response with this we have seen that yes we can create a post request with the with the data returning and with a nice status but what if we want to send the data where is the data so you can get the data here inside this store method by saying that hey there is a request and once again from nsgs common and i can import it i can say request and the type is the request so here we have to actually use this and the request is never used so i can just return the request and now let's see what's going to happen here so when i click on send something is wrong here it says request is not defined okay so i have not imported it i thought i have already imported it so it's a request from express and now everything is good click on send and once again 500 error this time it says that circular structure to json so it's having problem with this thing so what we can do to check what we have i just uh returned the risk request uh and then the request object i can log so that i can see here so once again click send request is there but all the request data is you can see here inside this but inside the request we have the body also so request dot body let's do this once again click on send and this time you can see whatever we have sent from our insomnia comes here now we can just return this like here okay so click on send yep the data we are sending from here is reflected back here now since we have the data we can do anything on this data but apart from these things like getting the route and creating something using the post route there is one more important with a get request for with a capital g for a user with the id so maybe i can say that hey give me the user id and return that user so get user i can say get users and this will be get user only a single user and this route will going to have the parameters or params so then we can just search for params param is user id and user id is going to be a number so comes with number something like this return user id and let's see what's going to happen when we send a request on localhost 8000 plus 22. send and now it says hey uh there is no post request yes there is no post request because we have a get request for that click once again it says slash 22 is not there so the problem is i don't have to use the curly braces i have to use this colon which define that hey this is a dynamic thing and now if i hit send you can see user id 22 is here this is the parameter which we are getting so i can just say that this is params and we can define this is going to be user id as number this is the simple type i have defined and then i can say params okay this is exactly same now since we can get this we can do the same thing for the delete route so if we want to delete something we can get the id and we do the delete part so delete user okay and do we have to import it yes i have to import it and similar to post request i can do one more for a patch request where i can get the user id something like this plus i can get the request also so it's for update so we need to import the patch also so now you can see we have all the crud related thing like reading storing updating and updating and deleting everything is there and this is a very simple way of working with nest js controller but it's not good to write all our logic inside the controller you know in programming in these kind of frameworks the controller should be lean and clean that means all the responsibility of doing the business logic should be somewhere else the only responsibility of controller is to handle the request and return the response nothing else let's see how we can tackle this situation now we have this controller which is handling the request not just for the get request but for post patch and with a parameter and for the delete also and we are doing all these things something like the user related thing so user then user id but it's all on the base url so you can see base url with this if i do something then we are returning the user id of 454 what i want i want to have the user something like this so if i do this all the the routes we have created here all these patch get will be prefixed with the user and now if i run it's not working because i need to give the user here which will be available here so in in the insomnia if i try i can show you that this is not going to work which is giving 404 but when i do the user and 22 yes it is working so then you will say what is the issue we have done that we have achieved it but the point is this app controller is a app controller we cannot fill this controller with every kind of route so what we have to do we have to create a dedicated controller just for handling slash user related route how we can do that we have to just create a directory called user and then inside that we have to create a user.controller.ts when we do that we have to export the class called user controller controller and to make this class as a controller we know we have to say controller like this and import this and very easily we have to give get request and here i say get user return i am from user controller and here i just define that all the routes inside this controller will be prefixed with slash route slash user now i will go to the app controller and then remove this thing so that this one is not going to be related to the user only user dot controller will going to work so is this going to work let's see if i go let's go on the insomnia and we have slash user slash 22 run it it's not working because we just have to give the slash user yes you can see it's returning user id with the user but this is not good why because this is actually handled by appcontroller because here we are defining something here so user id now it's treating user as the user id so this is bad so what i can do i can just comment this one and then once again try and now it says there is no route called slash user so what is the issue we have created this user controller.ts remember we need to register the controllers in our modules can we do that like register user controller here is this going to work let's try click send and yeah this is working i'm from user controller that's super cool and now with this i can go to the app controller uncomment this one because this one is only for let's uncomment it this one is only for the slash user is this going to work no it's taking over the user there is some complexity so what we can actually do we can move all these route from here from the app controller to the user controller like this and obviously importing each and everything so this should be get is already imported we need to just import the post then import the patch finally import the delete and also import the params and request so request comes like here everything is imported and now you will see that everything will going to work fine server is missing something what happened with the server server says that request is not defined i have forgot to import the request from the express.js and everything is fine yeah so now everything is prefixed with slash user so if i say 44 yeah it's working now everything is absolutely amazing we have done our task now our controller the app controller doesn't care about the user related thing all the user related routes are inside the user.controller.ts but still i'm not happy with this thing why because i have to register this user controller inside this app.module.ts which is not good thing so what i can do else instead of registering the user controller in our root module i can remove this from here and create another module inside this user directory so i can just create a new file called user.module.ts and export a class called user module and this class since this is going to be a module i will annotate it with this decorator and with a capital m and import this module this is going to have the controller defining here so user controller now the controller definition is inside the user module now we can just register this user module in our root module so how we can do that instead of controller i have imports so i can just say importing user module and with this we will be able to have the exact same effect on our insomnia so if i run it you can see it's there if i just comment this import you can see it's not there so everything is now everything is now dedicated to the user module now use its user modules responsibility to where is the controller where is the service what else we are using the root module doesn't care about how you have used the user related things it only care that hey i have to import user module and user module will take care about every other thing okay so this is good but this is not that good we can improve this one and we can do this things very fast how we can do let's see till now we have done everything by hand that means creating a file adding all these decorator adding each and everything from our hand doing everything manually so that's why we have this user directory where we have the user controller and the user module now i just want to change this so i'm just adding a underscore so that i'm not using this right now so what i want actually and okay so it's asking for import so i can just remove this import from here so that now this user directory user controller user module is not having any use because i have deregister or removed from the root module now what i actually want i want to create this net this controller and the module not by hand but from the cli the nest command line interface so when i just say nest you can see we can generate or just use the g flag to generate a lot of things application class configuration controller decorator filter and a lot of other things so what we need we need a controller okay before that what we need we need a module so we need a user module so how we can create that so i can say nest g for generate and then i say module and what is the name of the module i will give the name as user and i'm not going to give user dot module because nest cli know that you are going to create a module it will prefix everything just give the name so nest g for generate module and the name when i hit enter you can see it has done two important thing it has created this user.module.ts inside of this user directory this is absolutely important and it has registered that module inside the app.module.ts this is super amazing thing now you can see user module is there it's exactly same same what we want and in our app.module.ts it's already imported that's so great now we need to create a controller so how we can create a controller it's very easy once again nest generate controller and similar to that we need to give a user the name only and everything will be the same so if i hit enter once again it has done three things not a two it's three it has created a file called controller it has created a controller expect that means a test file for the controller and also it has registered the controller inside the user module that's so great thing now you can see our user module is already updated with this controller definition and i just put the comma to make the typescript happy and now everything is good what we just need we need to copy all these route we have given in by hand previously so i can actually copy that and go to the new controller and paste it that's it and let's copy the imports and do the import thing here now everything is exactly same so i'm going to remove the old user which we have created by hand and now we have a new user directory which is created through the nest cli and everything should work absolutely fine because now if i go try to run it yes everything is working as it was before how this is working because we have done everything with the next cli and it has reduced many tasks like registering the import of module in the root module registering the controller in the user module and all other things which we have to do from our hand and it has also created very nice testing directory which is going to be helpful for test of our controller so it says should be defined that means if there is a controller and we can run this one and it should pass which is passing yeah and we will not going deep into the testing so our task is to just understand the next js okay so this is the cli but now comes the very important thing which is the third third third important thing in the nest or third component of nest which is the providers and what are the providers why we are going to use we will see that but with this nest cli we can also create a provider or in our case we need the service so how we can create the service nest generate service for s and the name of the service so nest generate service of user so service for user and you can see in our user directory we don't have any service so let's hit enter and it has created three things one is a spec file for service one is the real service file and updated the user module if i go on the user module you can see on the provider list there is a user service and if you remember we know that all the services are injectable so we are going to talk about this service why we need it let's see with the use of nest cli we have created this user service.ts it's a normal class with a decorator of injectable but what is the purpose of this if we go to the user.module it is registered as a provider so user service is a provider provider that means it's providing something but in our case what this is providing so the name suggests user service remember i told you the job of controller is only to handle the request and give the response nothing else no business logic nothing so all the fetching of the things the data from the database storing things every other thing should be on this user service and this user service will provide the provide because it's a provider so user server we will provide all the business logic to the controller so how we can do that but let's learn about the providers first so provider in nest js providers are a fundamental part of nest js and providers are just a plain javascript class that are declared as a provider in a module just like in our user module we have defined this user service as a provider and i told you that classes such as services in our case user service repositories helpers can be treated as the provider simply by adding the injectable decorator which we have seen like here okay after that providers can be injected through a class into the class through constructor so how we can use these providers by having or by injecting them into the constructor nest js will handle the response resolving the dependencies and making dependency management extremely easy how this is going to work we will see in a moment and this is the thing so it's very easy and a simple you can say example of this service class is something like this this is exactly user service it's a cat service here we have to find two function one is for create one is for find and doing all the business logic here inside of this service class so this is the providers in the nest chairs so how we can use this first i want to create all these function related things like get user what it's doing it is returning a single user so instead of doing all these things here i can copy from here and move that logic inside this user service so i can just create a function called get user and return this thing now you will say that what are the difference between this get user and the function here inside this get user so you can name this service get user function you can name it anything you can just say get because it's a user related thing we know we are inside the user service so we can just say get nothing else and now we want to use that function here so it should be like i can comment it for now it should be like user service dot get we want to do this kind of thing from our controller in that way controller just need to know only one thing hey if you come to the get user route i want to call this function i don't care what this function is doing i don't care what the user service will do i just want to call this nothing else okay so how we can use the user service inside of the controller so remember i told you that provider can be injected into a class through the constructor and this is a normal class and yes we can create the constructor so what if we create a constructor and inside this constructor i can simply provide a private variable called user service which is a type of user service now if this is a confusing to you let me give you a better example so what if i create a const actually private user service like this i have created normal variable now from the constructor i will say hey this is a constructor and i will use the user service which should be user service like this and then we should say this dot user service is equal to user service and this code all these things is exactly similar to this code okay so i can remove this and we have a shorthand now this is user service which is injected into this user controller and how i'm saying injected means we don't have to care about the user service here all these things are handled by nest gs nest js when come to this user controller and it see that okay inside this controller the developer need the user service i'm going to instantiate it so let me give you another example we can also do this something like this i can say that hey user service is a new user user service something like this okay so this is the way we are doing this okay so we have this user service which is working now what if we comment this and uncomment this and then i say this dot user service dot get and obviously in our user service we have a get method which is returning this object is this going to work let's see first server is having no issue this means if i go to the get request on the user just on the user we should get this object returned cool so let's go to the insomnia click on send and you can see we are having this now to prove that this is directly coming from the user service i can go on the user service and i can change something here save this file go here click send and you can see satakrasto is there this means yes we are fetching this data from the user service now this way is normal this is not injecting we are not doing any magic thing we like the developer is instantiating creating the object of user service but next just say that hey you don't have to worry about how you can create a new object because what if this user service needs something else like like object b and maybe the object b will need object c as the dependency so that's why all these things will be handled by the nest gs by this kind of structure and we call this a dependency injection it's injecting but what we are injecting the dependency because this user controller class depends on user service and that's why dependency for the dependency on this user controller is the user service so dependency injection is a concept in programming where we inject the required or dependent classes by doing all these object creation of this class from the framework only we don't have to do this so we just change something like this and yes it is working absolutely fine so we can just remove this and cool we are having this right here right now similar to that we can do the things everything on our uh service so now i can say return this dot user service dot create because this is going to create and this is going to uh here we are going to pass the request now it says that you don't have a create method so let's go to the user service create a create method which is going to get the request which is a express request and for now i'm just going to re return the request.body that's it it's exactly same and same similar to here on the update i can say update and passing the request and i also want to pass the parameter so i forgot last time to pass the param so param is params or simply the param is going to be an object of user id as number okay so i'm passing both of these things like here and it says that hey you don't have imported param so i need to import the pattern but it has already imported what happened here so okay i have to call this as a param now that's good now update method is not there so similar to create we need a update update and this is not just going to get the request but also param and we know it's going to have a user id as number and returning the request.body and i can say simply say like body is request dot body and param as the parameter this is for update nice and then we should have returning for this dot user dot um a single user or or get user let's use the name get user and name it param not parents okay once again we need a get user or i can simply say user maybe it's it's not a big deal param is user id as number return param and finally we need to have the delete part so on the delete we also need to pass param not the params and making a delete function here so delete and everything is good and now i just want to make it show because it's going to show the user related things so let's change it to show oops good now you can see that the controller job is to just call the function from the service and nothing else everything is now handled by this service class or a provider class this is the way we work in nest chips now let's just verify everything and then we will move forward so yes user is working what if i say user 22 user id22 is there what if i post to something on the slash user yes anki is there now if i say 33 with a delete method yep it's there with the patch method it's also there we have a body and we have a param nice everything is working amazingly good in the last video we talked about the dependency injection but what is dependence injection we have seen that on our user controller we are using this user service just like this so the next gs is using the concept of dependency injection and it injecting this user service class in our user controller constructor so what is dependency injection so a dependency injection is a programming concept when class a uses some functionality of class b then it is said to be that class a has dependency of class b like the a need class b to use class b we need to create its object first so we do like const b new b but what if this b class also depend upon another class c then we need to do another object const c is equal to nu of c class and what if this c depends on d and so on so it's not possible in our case to add all these dependency one by one if there is a complexity so the transferring the task of creating the object to someone else and directly using the dependencies called dependency injection transferring the task of creating the object to nest js to the framework inside this nest js is the dependency injection and we just need to call this we don't have to care how you create the object next js will take care of each and everything so according to the principle a class should con concentrate on fulfilling its responsibility not on creating the object that it required so the job of user controller is to is to use the user service not to know how to create the object and this is the real good thing and that's where the dependency injection comes into play it provide the class with a required object so what are the benefits of dependency injection it help in unit testing because everything the object creation is take care of the framework and the someone else so that's why the testing become very easy we don't have to create the object even in the testing boilerplate is reduced as initialization of dependencies done by injector component so boilerplate that means the code you write is reduce we know that we have done the creation of this user service by doing the new user service it's not a good thing it has a lot of code against this a simple single line code okay extending the application become easier obviously when you don't have a lot of code extending the application become easier it helped enable lose coupling which is important in application programming and now what is loose coupling that means coupling means a connection between the two different things now user controller doesn't care about how you create the object that means user controller and user service doesn't have a tight coupling it's ha it has a loose coupling they don't have very direct relationship and that's very important when you write any code in programming world okay so this is about a short introduction of dependency injection inside the nest js framework till now we are doing and understanding the core components of nesjs which are which is the controller modules and providers inside this nest js but now it's time to learn about the request payloads so remember on the post request or the patch we need the request and we did this by using this request decorator which is providing us the request and from that request we get the body something like this but you know nesgus is powerful and it has done one thing for us for that let's go to the documentation and inside this documentation go to the overview on the controller on the right side you will see this request payload but before that you can just go to the request object and here you can see what we did is just like this request is a normal request from there express but apart from that request we also have a body this body decorator will catch only the request body part and we don't have to do this request dot body thing and this is really great so what i can do i can go to the usercontroller.ts on the post method where we are doing this request instead of that i can just say hey i need a body which is once again coming from nest common and then i can simply say body but what should be the structure of this body this is interesting but for now i just say any to make the type of script happy and just pass the body when you pass the body inside the service that means on the service we don't need any request we just need the body and we can return the body as it is let's see if this is working or not so here we have a post request on slash user and if i click on send yes we are getting the same data as we already have so this is super super easy and very nice so we can do the same thing on the patch because here also we are using the request we don't want so let's have the body and we call it body for now it's anything and i can pass the body here so since we are passing the body here go to the app user service here also it's a body and do the anything and we don't need the body here and one more time go to the slash 44 with a patch actually you can name it you can give any number it doesn't matter for now it's totally just for learning and oops it's a patch request now you can see we are back with the same thing this is super great but let's once again go to the documentation and on this documentation we have a request payload now when we say the request payload that means what we are getting from the request see here when we say on let's go on the controller when we go to the patch we are having this body and body is any that means we don't know what things are coming so for now i'm returning name and email what if someone say token and passing any random token what if this is there and it's just going to work okay something is wrong here so what happened uh uh uh okay i think i need to use double quotes yeah so now if i send it you can see i'm still getting the token which maybe i don't want so we need to properly define the structure so this is the thing where the nexus documentation will provide you very nice information so what we need to do we need to create a dto what's dto data transfer object schema so here we are defining what will be the structure of our body now instead of calling it as a body i can say update user dto and this should be like name as string and email also as a string very nice so now i can just pass update user dto and just change the name on here and it's update dto update user dto and also give the type like here instead of any i'm providing this like here cool now what if i run it again and still we are getting but at least we have defined this thing and we know what we need here that's good so here we have this but you can see that we are defining this uh you can say the type for update user dto the body thing two times one here in the controller another here in the service we don't want to repeat ourselves we want the dry code and that's why we need to create a class called dot dto dot ts and here inside that we need to define the structure and we can export and then we can simply use it but question comes where we have to create it inside the user we can create a directory called dto inside that i can create user create dot dto dot ts inside that i just say export is this a interface export class you can create a interface you can create a class it doesn't matter so create user dto and then we can pass this thing here like this and let's use create oops it's update actually so i need to change it to user update and here update user dto so update user dto comes here that's cool and same we can do on the controller also so instead of that i just need to import it and that's it everything is good we are back with the same thing so everything is working but this time we know that this body is having this kind of structure which only have these two fields coming whereas that user update dto is here okay so we can change the name something like update user dto and it will change the imports very nice cool so i have some problem here on the declaration okay so somewhere we it has not changed it so update user is there where is on the service update user is still there yeah it's working fine cool and finally similar to this we can also create a create user dto which is almost similar create user dto something like this and it should be with the dot ts also at the last and we will update it if we need according to our need okay so this is good and we can use this on our controller so where we have the body we can say create user dto is a type of create user dto like this and it says body is not found because create user dto is there okay and problem is here update user dto why it's giving error everything is fine okay ah once again i did wrong so i change it here so this is good now everything is working cool fine this should not be from update this should be from the create file cool this is this is good and now go to the service and here also create user dto data transfer object and create user dto and return the create user dto like here everything is good but we have the problems the problem is we are returning uh the token also i don't want this token also what if i am not giving any email thing inside the email or maybe i just give a number inside the email right now it's accepting everything let's call about the validation inside the next chase to talk about the validations in next once again i can take you to this documentation website but not inside the overview let's go to the techniques and here we have the validation now we can start by validation by installing these two dependencies so let's copy this and go to our application and install it well this is installing let's see what next we have to do it says that first we need to install it then validation pipe is exported from next.js common package okay everything everything is good for us how we can use this this library or dependency so first we need to add this as globally and global pipe now what is pipe so first go to the introduction and overview and here we have a pipes so pipe is a class annotated with injectable decorator so if it's injectable that means it's a provider but it's a transformer so it transformed the request data so what is the use case of this pipe transforming the input data to the desired form and validating so validation evaluate input data if valid simply pass through it otherwise through the exception there are couple of uh you can say inbuilt validation are there so what are the inbuilt validation first you can see validation pipe which we are going to use with the validation then we have a parse into parse float parse boolean we will talk about them later but let's once again go to our technique and validation and here we need to register this in our main.ts so we need to use this thing so copy this and get back here it's now installed go to the main.ts after we create the app we need to register it and let's import this like here okay now we have the validation pipe imported and now we are ready to use the validation things so the question comes how we can use the validations so remember we have created the dtos to create the user now in our ddo we can define that this field is a email field this field is not empty we need this it's required or various other things so let's go on our update user dto and here i just need a decorator called is a string because this is going to be a string thing and what about the email email is email validation okay now we have this email validation so this means remember we are using number inside the email is this going to work let's click on send and now you can see it says hey status code is 400 and email must be an email and that's very nice so i can get back the email but i want to change the name to something uh alphanumeric or maybe just a numeric send now it says hey name must be string so that's why we have a very nice validation so this kind of validation you can add to any place so copy that and we need the similar kind of validation inside our create dto also so import these things very important now what next we have seen that something like this we can also do some kind of validation on the params we will see that later but right now we have another issue which is pending for a long time what's that it's now taking the unknown field from the request i don't want to get the token whether someone is passing token or not i only want to accept name and email how we can do that so we have this validation field inside that we can see we have somewhere yeah this one stripping properties so it's saying that if you say white listing is true in that case it's only going to accept the field which you require so i can just enable this white listing from here and for that we need to go to the main.ts where we have defined this pipeline inside this i can just provide that white listing is true while once i did that i will be able to see that hey if i send a request whether i'm passing token or not it doesn't matter we only care about the name and the email field which is extremely extremely important when you work on any crud part i told you that we can also have the validation in the parameters so params so if i go to the controller yes we have the dto in our body but what about this params can we do something for this also actually yes we can create the dto kind of thing here but we also have a very nice little pipes thing so go to the overview and the pipe here we have inbuilt pipes available so pipe in parse int pipe what that mean if we know that user id is always going to be a number then we can say parse int now for here we can see that when we do a get request on user 44 then we are returning user id as 44 but here you can see it's a string not a number so on this um get part where we have get the user like here we are saying this is a user id but how we can add the pipe let's go to the documentation and it says that when you define the parameter you can define what parameter you actually want to get then change the type or do the pipe thing here and then define it like this so instead of doing the params and user id like this i can say that hey from this params i only want the user id and this is going to be the parse int so into pipe and then this is just user id which is a number and now we can just pass the user id okay so since we are passing the user id like this if i go to the show method inside the service user service here we just need to say hey i need a user id which is a number and nothing else user id this is the way we can clean our code and now if i hit send you can see we just have this 44 and we can say that hey user id is the user id we have like this and this time it's a number now what if i provide some string so if i send it this is a very nice thing that since we are expecting a number here where is that since we are expecting the number here if we pass any kind of other than number thing then we are getting the validation error and this is the pipe validation not the validation we have created and by doing this we are cleaning up our code and doing the validation right here at that pipe thing so once again user id parse int pipe and user id is a number and pass the user id and that's it on the delete method instead of this i can just get something like this and user id okay so once again on the delete here we are getting the validation error but if i say any number we are getting the number and the last but not the least we need the user id here on the update part as the number and i can say user id like this so it should be there okay so maybe i can do something like this user id here and then on the controller where we have the update part we can do the exact similar thing by copy from here and paste it here and pass the user id that's it and final check with the patch getting the body and getting the user id right here so this is all about the pipe and the validation in nesjs we are doing some kind of crud but it's not exactly the correct because we don't have any data storing anywhere so let's now work on storing data inside a database for mysql so first i will go on the documentation and on the documentation you need to go first here on the techniques and here we have a database and they have given an example for mysql but you can use any database you want okay so how do we get started we need to use a type o rm now what is orm object relational mapping so this actually makes your life easy you don't have to write any sql image sql query not image so you don't have to write any select everything from or alter table or any kind of things also this is not specific to mysql you can use different kind of database but having but writing the same exact line of code for fetching or storing and doing the database related things so that's why we need to install this thing type orm for mysql cool let's install this one in our system and then we will see how we can move cool so then it says that how you have to define the my sequel related um the informations like the the host name the port user id password so here inside the app module remember the root module we need to define this with the type orm module dot for root we want to access the database from entire project and that's why we are registering this inside the app module so let's copy this thing from here and go to our app.module.ts and here we have this import for user module and after that we also need another import for type orm module so now let's import it because this package is installed and then we need to change our things so username is root password is password or database name is nest js and this synchronize is true and remember this is a warning that it's only true for development and should not be used in the production otherwise you will lose the data so it's actually going to clear your database i think once you start working on it so first i will go on the terminal and log into my mysql and i remember that my password is empty like here so here i need to say create database called nest js and that's it we have done that so show databases databases like here and now you can see we have nest js cool this is done and we have connected what next to work with the database we need to create a file called entity and now this entity is for the user so user entity dot ts we need to create inside our user directory because everything is related to user and this is why we have it so we first create a directory called ntt oops ntt like this and inside that i'm going to create user entity dot ts file and as usual this is going to be a normal user class so export class called user but to make this as an entity we need to say it's a entity and this comes from the type orm not from the next js this decorator is for type orm now what next we need to define the structure of our user model or user table i can say so in our case user table yes it should have a id number and that should be the primary key so let's define that id is going to be a number and yes but let's have the decorator of primary generated column okay then we have a name which is going to be the string and this is a normal column like this and also we need another column which is going to be the email and we have the string that's good and we need these things we don't want this but yes you can have it we have done with this but how we can use this entity in our user module so then it says user entity file sits in user directory and user directory has user module so you need to register it like here on the user module you need to say hey i want to import a module which is a type or a module but for the feature of this entity okay so let's go to the user module user.module.ts here i'm going to import not like this one yeah and now i say type orm module and this type ora module is dot for feature of inside an array i want the user which is coming from the entity the user entity that's good so we have connected the database connection is there then we have created an entity which is having the structure of our table and then we tell our nest js that use this entity by user.module and here we have defined it now what next it says this module uses for feature method which define which repositories are generated in current scope now to use this uh this this type of rm thing from our controller to our user service we again need another thing which is called injecting a repository this is using the repository pattern the type orm uses the repository pattern and on our service class where all the business logic is is there we need to create a constructor where we get the repository through the entity we have created okay how we can do that let's see so here we are on the user service let's create a constructor inside this constructor i need a simple private user repository so private user repository and this is going to be the repository from the typo rm having the type of user entity something like this but we need to add this decorator so that our nest js will be treat this as the type orm thing so just above this just above this private thing i can add something like this and import it right here so inject repository when coming from nest type orm repository is coming from directly from the type orm and we have this user repository now when we want to first get the data from the database we can do something like this this dot user repository dot find which is getting all of the user if we want to find a single user then we need to pass the find one with the id we can delete something like this and we can also do the store part okay that's good and let's test this out so how we can test we can use this code first when we get this when we had have this user repository get method where we are fetching all the user information i can say this dot user repository dot find and we have a very nice autocomplete so you can see if i say find it's all there but this is a database query and database query takes time so what we need we need to make this as a promise which is returning a promise that hey i'm promising that this query will going to return array of users okay so we can define that hey this is going to return a promise of user which is class imported from user entity and array i'm doing wrong something oh yeah i need to define it something like this as a promise not like that okay so this is good we have defined the promise and let's check this out on the insomnia when we try to fetch or get uh all users let's see what's going to happen okay so server is not happy with us it says something and first it says typeom unable to connect to database retrying it's not able to connect to the database we have some issue with that unable to connect database once again so open the app module and here we have nest js and show databases nest gs is the database name and localhost 33.0 root is there what if i provide type password as null and restart the server once again let's see what's going to happen unable to connect to the database retrying once again and i need to find the solution for this now as soon as i change from localhost to 127.0.0.1 it is giving no error so this is good and now once again go to the insomnia and try to hit send and this time it's not giving another like server is not there it's giving some 500 error which is having some different thing it says no metadata for user found now what this is this exception is saying that i don't have any information for the user so here on the entity we need to define we have an entity for user once we do that we can once again try and hit send and you can see this time we are getting empty because yes in our database we don't have anything but if i go to the terminal and if i use the nest js database and show the tables you can see we already have a user table now if i say select everything from user you can see this data if this table is empty now let's move to the create and other part of correct related thing through this mysql through this type orm inside the nest js right now we have nothing in our database although the table is created but let's see how we can fulfill all other things so we have this user entity where we are defining all the user structure and using this with the help of type orm we will be able to do the query on our database directly now this user repository is going to find all the user but since we don't have any user so we are getting empty so first task is to create a new user how we can do that in this create part instead of just returning whatever we are sending in the body i can say this dot user repository dot save these data we are providing inside this create user dto that's it we just need to do this and since everything is uh dedicated to the user service so we don't have to touch any other code if we want to save in a different way so user controller just know that it has to call the create method on the user service and now it's user service responsibility how it store the data into the database so we are going to use the repository save and create video that's it let's now try so with a post method on this user slash user url i'm sending these three things remember i'm sending this token which is additional data we are sending but we only going to save these two things and if i click on send you can see we are getting an id plus the name and the email this means we should have the data in our database so if i go on the my sql you can see we have this data this means when when we go on the get part when we send now you can see we have one data let's register another user here so sarthak sarthak at bitfumes.com and remove the token it's not needed okay now click on send we have another user so get all the users and yes now this time we have two users from our database that's good now since we have two users can we get the user one or user 2 information so if i want to get the user 2 information can we get that right now we are just returning the user id let's see how we can find it so on this user service once again we have this show method where we are showing a user once again we say this dot user repository dot find and finding with the user id but we don't want a lot of user we just want only one user so we can use the find one but then we need to define the where condition so i want to say where id is equal to user id just like this and it says some error is there something like this cool now let's try this i am on get method of user 2 so yes you can see i'm getting the user 2 information if i say 3 i'm getting the third user information but it would be cool if i just call this as id and then i don't have to write it like that i just say where id is the id we are passing and that's it it's exactly same so we did this with the find one so post is there that means we are creating we are fetching one now let's work on deleting and then we will work on the update so delete is super easy this dot user repository dot delete and delete with the user id is there and that's a super easy task so i just want to give a delete method from the insomnia to delete the third user and click on this and it says one row is affected that means if i try to get all the users we should only have one user in our database which is anki cool so we have seen that how we can delete now it's finally time for the update in the update method we need to pass two things the user id and the body also so this dot user repository dot update and the first thing we need the identifier this means the user id and second is the update user dto just by doing this we will be able to update our request so here we are let's first create the third user let's first create a new user not a third or fourth now the user is created and i want to update this fourth user so i want to send a patch request and i say the surname is the start action also this is the full name and click on update it says one row is updated get the fourth user and you can see name is now updated so this is the way we can have a full crud application from the nest chest using mysql as the database the most important part of any web application is the authentication and we are going to follow this documentation from nesjs to understand how we can set up the authentication system in our existing next year next js application so first thing we need to update is user entity now along with the name and the email and the id we also need one more column called password because we are going to store the password thing in our database also with this thing we also need to update our create user dto which need another field called password which is going to be a string and is is there any password thing no but is going to be the string okay and similar thing we need on our update user dto like here cool so we have done that but do we need all these things and is this going to work when we create a new user so let's see what if we have to we create a new user how this is going to work so first important thing is we need another username so maybe john and email is the same and you can see what if i give this a send now it says password must be a string so password we have not defined so let's say password is going to be secret123 and send it here you can see we have the field password which is updated on our database so you can see now we have john with the password but anki and sarthak doesn't have the password field okay that's not a big deal we can remove these two users so we can simply say user 2 remove and user 4 also remove okay so we just have one user with the password field as one two three so let's create a login route and we will see then how we can log in a user so very nicely we can generate a controller called auth controller and this is going to create a controller inside our auth directory and update the app module so we have this auth controller inside this auth controller i'm just going to create a post request with um say slash login and this is auth so controller is prefixed with auth now i say just login is a function which is just going to return i am login okay everything works fine server is okay so let's go and say login auth slash login and with the post request send and it says i am login that's good but what we need when we want to login we need to pass the email and the password field so we need to get these field on our function so here we can say hey we needed the body and the body is actually going to have the the login dto dto something like that so we have this and we can define this as any for now and i can use this and return it like this so we need to import this body and body is imported decorator is expected and something is bad happened here oh i always forgot to call this decorator cool everything is fine send it once again and yes we are getting back the user with the password now what we need we first need to find the user and then we need to check for the password so how we can find we do not have the user repository here so how we can use the user repository in user service we did something like this thing user repository but instead of using user repository we have this user service which is going to find or show a user okay so this is really good function which we can easily use but instead of this show with the id we need to find find the user with the email so let's create another function called find by email where i get the email like here and then i return this dot user repository dot find one and inside that i say where email is equal to the email we have passed like this okay now we can use this function inside this body this means we need the user service as the dependency injection is all inside auth controller so we have something like this so private user service is going to be user service and that's it is this going to work let's see so first we say this dot user service dot find by email and then we say login dto dot email because inside that we know there is an email is this going to work let's once again try okay server is not happy with this thing so now what it says nest can't resolve the dependency inside the auth controller so we are trying to use the user service but this controller is auth controller doesn't know from where it can get the user service but why because auth module is missing and we are not hap we are not having any way of telling that auth controller is there so in the app dot module we have the auth controller but app module also doesn't aware about the user service so how we can do that so we have to do two things first we need to create a auth module so nest create a module called user sorry auth not user so auth module and it should be available here auth module is there and app.module is updated with the auth module now we don't need this auth controller from here because auth controller is now defined inside this auth module so i can say controllers is going to have auth controller okay still we are done with the auth module but server is not happy because it doesn't know how to resolve this user service but why see there is two different module one is a user module and other is the auth module where we have a user service we have inside the user module so user module know about the user service but auth module doesn't know that there is something user service so what we have to do from our auth from our user module we need to export our user mod user service actually like this now when we have exported from this user module we need to import full user module which is only going to give this user service as the service but where we have this auth module inside this auth module i want to import user module now when we import the user module do we mean that we are importing each and everything no we have only exported user service this means when we import any module inside other module other than root module so when we import user module inside the auth module then it is only going to catch or it is only going to use the services which we have exported from the user module and that's why if i now see server is happy with this and now it should return us the user so send it and you can see user is here so we are having the user so we say hey const user user is there and if there is a user then we do something otherwise return null or simply we can say unauthenticated like this and this is not a good thing but just for now it is okay but what if we have the user if we have the user then we will first check user dot password is exactly equal to the login dto dot password if this is true then return the user otherwise return password doesn't match okay and now it says since it's returning the promise i need to maybe i have to use await here and if i'm using await i need to say async and yeah so now user is there if i change any password yeah password doesn't match cool so we have given a very rough login login route we have created an authentication a module is there which is handling the login route which is checking for other modules which is importing user module and inside the user module we are exporting only user service wow what a code we are doing this is nice but we need to move forward on the authentication why because inside this authentication we really want to check for all other things and now we will use the passport package so if we go on the authentication part it first says that you need to install the passport we have not done that but no worry we will follow this documentation very nicely we have created this rough login route but now it's time to use the passport package so let's copy this and install this one and also the type system for this passport so this is installing in a new tab i can install this thing both are installing so what we need to do next implement the passport strategy so we have created these things the module is there but now for auth we need to create the service also why because i told you this controller doesn't know about the business logic what is the role of a controller to handle the request and return the response that's why on the auth module we need the service so now we are creating the service and you can see the auth service is created and auth module is updated with the auth service okay so we have created that and both packages are installed let's move so then it says on the user service you have to create find one which we have already created that we know and then it says on the auth service we just have created you need to create a function called validate user remember inside our controller we have this thing which is validating if there is a user of that email and the password or not this is exactly the this business logic we are going to do inside this auth service so async validate user and this function is doing all these things so first we get the user and we check for any other thing and then returning all these things it's returning a promise for any and it need email and password in our case so we can just open the controller cut everything from here and paste it and since we need the user service here we can move the con constructor where we have the dependency injection for user service now it's inside the auth service and since this is actually exported from the user module like this and the full user module is imported inside the auth module we are happy with this dependency injection and server is happy here also although it has some other error we can check it says logging dto is not there maybe we can just say i need the email as a string and the password as the string and now instead of login dto dot something i'm providing this thing cool so everything is there and now when we want to use this we can first um create a constructor inside we can say private auth service sir wait sir uh sir who is sometime i forgot the spelling auth service is there cool and now i can return this dot service dot validate user and passing login dto dot email comma login dto dot password okay this is nice controller doesn't know about the business logic it's just calling this validate function and that's cool on the auth service we are having this still we are not doing any passport thing so what next after doing that it says that you need to add your auth service to the provider auth provider yeah auth module provider is already added then it says implement the passport local this is the real important thing inside the auth directory let's create a local strategy what strategy is doing strategy is actually checking for the user validation and if it got the user then it returned the user otherwise it will throw the exception and this is all the passport related thing so let's create a local strategy.ts file inside this auth directory so create a file localstrategy.ts and then i'm going to create i'm going to copy all these things and paste it and see what we need or what not so local strategy is extending the passport strategy where we are having some kind of a strategy coming from a passport local then on the constructor we are getting the auth service we know this is the dependency injection for auth service we have just created to access this validate user function and it's calling super so that the passport strategy class will also get something on the constructor and it will be there finally on this local strategy we need a validate function which is going to use the email in our case and the password and then we pass the email on the validate user which is returning the prop promise for any and unauthorized exception if we don't have the user okay so is this going to work we need to change our code little bit it says that if we don't have the user we need to return null and if password is also not matched then also we need to return null is this the same thing we can verify from here see if user is there and its password is matched we can do the same thing by doing all these things in one go if user is there and the password is matching with the password then return the user otherwise return null let's check this out is this going to work our insomnia is here password is incorrect obviously 1 2 3 but it's 1 3 let's run it it's not returning any response this is not good it's actually returning null what if i say 1 2 3 and send we are getting the user so what happened actually we are using the local strategy but we need to bind or we need to tell to the next js that hey nsgs whenever you use this logo this post as a login you need to take care about the passport strategy also how we can tell go to the documentation and here you will find after that first you need to go to the auth module and then you need to import passport module and provider the local strategy so go to the auth and in the provider it's local strategy and importing the passport module both module and strategy is imported and after that we need to do something like this we need to add this use guard look auth guard of local okay an auth guard is coming from passport so we have just imported these two it is not working see it's still returning null but go to the controller and above this we can add these things and import these two and it should now do the magic click on send and you can see now since the password is incorrect it is saying unauthorized and status code is 0 1 4 0 1. if i provide the correct password it should not return this thing i think we have some issue so what happened here is the problem we are facing is on the local strategy the local strategy actually need the user name but what we are doing we are doing with email so we need to explain to our passport that hey passport i'm going to use the user field as the email just by doing that now if i go on the insomnia if i send it with the correct details like this you can see now we are having the user so this is the simplest way we can add the authentication with the passport thing one more important thing is there we are doing all these things from the auth service now since we are using the passport we don't need to query through the uh through the auth service why because when we do the passport thing then we can use the request so request if i type correct like here then we get request with a type of any and now i can return the request dot what's this equals dot user so what this passport will do passport is actually going to insert the user in your request so we need to make sure this is imported and always forward to call this requested decorator now once we have done with this then if i once again send it it's returning exactly the user because this user is inside our request i can log this and see that hey the request is really inside the user is really inside the request so send it and we have full user information full request information and inside that request we can find somewhere there is a user which is here so we eliminate the use of this auth service directly inside the controller and in that way once again the controller is lean and clean and it doesn't depend upon other things which is really awesome what next next we need to follow up this documentation and we will see what we can do else inside this authentication whenever we login a user with a correct email and the password we are getting back the user detail but what we need in general api we get a token a access token which we can use to access any protected route so let's see how we can implement that for that we need to go to this jwt functionality inside the authentication and we need to install this package so copy this and paste it also the types for this passport jwd which is there then what we need next in our auth service dot ts we need to have uh on the constructor and then we create a function where we create a new token with the payload of the user details let's see how we can implement these things so first we need to open this auth service in this auth service we have this user service inside the constructor similar to that we need the jwt service which is jwt service something like this okay and sir ways good now just like this validate user function i need another function called login inside this i will get the user and from that user we can extract the email and the password email and the user id actually so we say const payload is equal to an object with the email of user dot email and sub is going to be user dot id so we have user dot id dot id and then we get the user and this is going to be any for now once we have the payload then we can simply return an object which is having access token where we say this dot jw jwt service dot sign signing with the payload once we do all these things it will going to work and yeah so we have implemented this jwt service we have created this login route a login function not the route login function what next once you have done with these two things you can create a jwt secret constant although you can have this constant in your dot env file also but let's have this somewhere on the auth we can create auth.constant.ts and have this just like here and then we can go to the auth module and register our jwt module with the secret and the sign option how go to the auth module on the providers we on import actually we have these two next will be jwt module inside this jwt module i need secret and secret is from the jwt constant dot secret which we get from our constant file which we have just now created and it has to be jwt dot register actually that's why it's giving error so jwd dot register and after that we need a signing option and signing option need the expires in time so we need this expires in time just by doing this we are ready to use our login function which we have in our auth service but where we can use it we have to use this in our login route inside the controller so it's going to be really easy because now login function is inside the auth service so auth service is having this login function so go to the controller and here instead of request i say this dot auth service but service is not present here so we can actually get from the constructor private auth service is auth service like this and now i can say odd service dot login with the request dot user that's good we have done this and now let's test do we get the token or not so everything is good let's click on send and yes you can see we are getting this authenticated authentication token which is a gwt token and now our our task is to create a protected route which can be only be accessible with this token otherwise if token is incorrect or token is invalid not available then that route will be not accessible by any normal user how we can do that once again we need to follow our documentation and then we will see how we can use a protected route with the token we have created once we have this token we need to create a protected route first so that we can access that protected route only with this token how we can do that first go to the user module and inside the user controller we have all these user related things or maybe what i can do i can generate a new controller and first i will create a module called profile and after that i will create a controller for the profile controller okay now another module is there and inside this module you can see this profile module is also added on the root module and inside the profile module we have the controller and now on the controller we can create a route called with a get request for get request and it's like a profile and then this is going to return like i am protected route okay so since this is this should be protected route it it should not be accessible via normal user so what if i say profile with a get request you can see it is returning this i am pro protected route so maybe i can do something like message yeah okay so we need to make sure this is only accessible via the token the access token of the user for that we need to work on jwt strategy remember we have created a local strategy for passport so similar to that um local strategy where we have created that yeah this is the local strategy similar to this we need to create a jwt strategy which is going to resolve the user from the token okay so once again on the auth directory let's create auth dot jwt strategy dot ts not auth so it should not be prefixed with auth or it doesn't matter actually but what we need we need to extend passport strategy once again it is going to be similar to the local strategy similar similar to this but this is going to be the jwt strategy so export class jwt strategy strategy yeah extends passport strategy with with a strategy as this and now what need what this need this need a constructor first it need a validate function so let's create a function a sync validate this is going to validate our user so that means we need to pass the payload first payload type is any for now but then we say return user id payload dot sub user name payload dot email so we just return id as payload dot id and email as payload.email and why i'm doing this idn email because remember in our login in our auth service on the login part i have email and sub so it should be sub not the id this will be id and payload dot sub okay so this we have done that very easily but we need to extract the detail from the header of the token so from the constructor we have to use all these codes so it's little complex code so i'm going to copy that and paste it here which is saying that you need to first have extract jwt from auth header as bearer token and then jwt constant we need ignore expiration this is just for local you can make it true if you want uh in the production or in the local whatever you want but this is jwt from request is the thing we need okay so this is done everything is okay for now but once again we need to make this class as injectable so don't forget to have injectable decorator here and now this jw strategy is done remember we have used this local strategy in our controller by auth guard of local similar to that we can use that um auth guard of jwt but before that we need to register we this our our jwt strategy in our auth module so auth module is having this local strategy plus jwt strategy so all these strategies are there and now go to our go to our profile and here let's have this use guards auth guard of jwt is this going to work let's see so first i will hit and now it says unauthorized so this means we need to have a new token so i'm going to create a duplicate token and here it should be we can name this how we can change the name anyways so new request is this token should be from here so auth slash user and with a post request what happened auth login yeah auth login is there i get this token so i can copy this token from here go to the new request and in the auth section when i see header i can say authorization is bearer token okay send this and now you can see it says i am protected route but when i disable this bearer token it says unauthorized so cool is that we have implemented this jwt token and with this token we will be able to have some protected route which is only be unlocked with the token so this is all authentication system in next js and i hope you found these things very easy to learn and easy to apply for your next amazing nest project okay so i hope you like this videos and share this video with your friends don't forget to subscribe and like bit fumes on facebook twitter instagram and linkedin subscribe is must and if you have any request for anything related to programming just comment below i will create a full video on that see you in the next video
Info
Channel: Bitfumes
Views: 78,081
Rating: undefined out of 5
Keywords: nestjs tutorial, nestjs vs express, nestjs authentication, nestjs microservices, next js full stack, next js full tutorial, next js full project, next js crash course, next js full course, next js advanced course, nestjs tutorial for beginners, next js tutorial, best nestjs, best nestjs course, best nestjs tutorial, nestjs course, next js crash course 2022, nestjs authentication jwt, nextjs auth, nestjs database connection, nestjs database, nestjs modules, what is nestjs
Id: Mgr5_r70OJQ
Channel Id: undefined
Length: 158min 23sec (9503 seconds)
Published: Tue Jun 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.