Nest.js Crash Course 2023: A Comprehensive Step-by-Step Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to Sakura Dev Channel this video is a crash course on sjs while Nest series is a powerful back-end web framework that is built on top of the node.js which allows developers to build scalable efficient and reliable server side application in this crash course we'll be covering everything you need to know to get started with nest.js from setting up your project from scratch to creating controllers Services modules and also connecting to a postgres database with type program and docker and in the next video we're going to talk about how we can Implement authentication and authorization in SGS by end of this video you'll have a solid understanding of fundamentals of messages and be able to create your own back-end API using this powerful framework so whether you're a seasoned developer looking to expand your skill set or a beginner just starting out in web development just grab a cup of coffee and join me as we dive into the world of nsjs in this section we are going to create a niche JS projects from scratch in order to create an sjs project we should install the necess CLI so I go to the documentation of the messages and the introduction section of the documentation has a script for installing the necess CLI so I copy that and I go to my terminal and here paste that script which says the npmi the SG at messages at CLI so I use Dash G because we want to install the initial CLI globally after installing the nsjs CLI we can initiate a newness.js project so in order to do that I'm going to say nest new and then my project name for example I'm going to say nist Dash crash course and hit enter and it says which package manager you would to you would like to use I'm gonna go ahead with the npn and then it is going to install all of the dependencies that needs to this project need and scaffold our project okay it's finished and now we can go to the nest crash course directory and then open it in vs code let me make it a little bigger here as you can see we have a SRC directory and inside it we have a main.ts file this file is our entry point of our application as you can see we have a bootstrap function and inserted a new series application is created with the nest Factory function and then it will listen on the port 3000 and then the bootstrap function is run and the application will be run on Port 3000 if we want our application we run on another Port we can change it here for example if we want our application to be run on the import 8000 we can change it to 8000 here so this is the entry point of our application and again if we look at the SRC directory you can see we have a app.module.ts so every next JS application can be divided into multiple modules when we create a new project in messages it comes with the app.module.ts which is our root modules and also each module can have other module inside it as its child module so we can consider these module structures as a tree structure where each module can have its own child module so in this way we can divide our application into a hierarchy of modules and also each module can have its controllers and services so in the controller we Define our API route and in the provider or Services we Define our logic so as you can see this module has the app controller so if I open it which is in the app.controller.ts file you can see it has a app controller class and in which a get request is defined so we can Define the get request with the get the query tool which comes from the initials slash camera and then map it to a get hello function here so this function in turn calls the get hello function from the app service so if I go to the app service here in the app.service.ts file you can see the app service class has a get hello function that returns just a hello world string so when the get request is coming to this controller it calls the ghetto function from these services and then return the value of git hello to the clients so now if I run this server with npm Run start you can see the application is running on the port 8000 and if I go to the insomnia and send the get request to the HTTP localhost Port 8000 in which our list yes application is running and hit the send button you can see that the hello world string is returned to the client as the response of this get request to this root route our application so that's it the introduction section of the nsjs and in the next sections we dive into details of each of the controllers modules and services yeah from this point on we are going to create a project and take this course forward with it this project has a bunch of users and each user can have several comments on a certain topic so this project has three entities users comments and also topics so we are going to divide our application into three modules user module comment module and also topic module so to begin with let me create the user module first in order to create a module we can do it manually or we can create it with the help of the necessary so I'm going to create it within scli so I'll go to the terminal of the vs code and say nest G which stands for degenerate and then module and then name of the module which in this case is user so as you can see it creates a user.module.ts file and also update the app.module.ts so if I go to the SRC directory we can see that there is a user directory which is created but in scli and here we have the user module and also if I go to the app.module.ts file which are root module you can see that it Imports the user module and this means that the user module is the charge module of our root module and in The Next Step I'm going to create a user controller inside the user module so here I'm going to say nest GCO which means we are going to generate a controller and then name of the controller which is user and then we can specify dash dash no spec which means that we don't want to create a test file for the controller so if I hit the enter you can see it creates a user.controller file inside the users directory here you can see it creates the user controller and then it updates the user module so if I go to the user module you can see that the user controller is now inside the list of the controllers of the user module and if I go back to the user controller you can see it just a class which is decorated by the controller decorator which comes from the nest.js slash command inside this controller decorator we pass a user string which means that every API route inside this controller is start with Slash user and for example if we want to define a yet request inside this controller we first of all add a get decorator so I'm going to say add get which means that we want to define a get request and then import the this decorator from the nsjs slash common and then Define a function for example I'm going to say find out and here this get request is mapped to this function so for example we're going to return all user for now and now let's run the project so I'm going to say npm run stock and then call on dev which watch for the all changes inside our projects file and if any changes is committed to the files of the project it will restart this server so if I hit the enter and go to the insomnia and here we can add a slash user at the end of our backend server and send a get request and you can see that the all users is returned to the insomnia client so here you can see that inside this get request we didn't pass any path so we can add a path here inside this categories for example I pass all so now if I go back to insomnia and send the request to the slash user it says that cannot find the get request of Slash user but if I add a slash all to the slash user and send the send the get request you can see we get the all users so if I go back to the vs code we can see that this get request is mapped to slash user and then slash all foreign we can also Define plans for our API routes for example if we want to pass the ID prompts here and we just have to put a call and then name of our prompts and then inside the final function we can use the program decorator which comes from the nsjs Canon and then inside it we are going to pass the name of our params which is going to be the same as here so our problems is ID and then we can have it as a parameter inside our find all function so I'm going to say ID and its type is string and then we can return an object for example and says the user and then inside it the ID is set to the ID parameter of find all function so now let's save this and go back to insomnia and for example I'm going to say user slash 53 and then send and you can see that it sends us a user object with the ID of 53 and now if I change it to for example 10 you can see that the ID is changed to 10. so in this way we can capture the params inside our growth Handler okay now let's define a post request for creating a user entity so let me close this off here and then here I'm going to put the add post equator which again comes from the initiate slash common and then Define a function for it for example create and then inside this function we can return this route is for create a user so now if I go back to insomnia and then send a post request here you can see that this route is for create a user we can also pass a Json object inside the body of this post request to this API so here inside insomnia I I create a Json body and inside it for example I'm going to say name and set it to John and then I go back to the vs code and inside the create function we can access to the body of this post request with the body decorator which comes from Netflix common and here we can define a variable called body for example and set it to any for now and then just return this body KFI hit the send you can see we have a object as a response of this post request which contains the name and is set to John we can also access to specific properties of this Json object for example we can specify that we want the name from the body and change it to name which is going to be string and then return the user name is and then concatenate the name parameters so if I go back to insomnia and hit this end you can see that the username is John so in this way we can access to specific property of the body object it sounds great but in this shares offer a more advanced way of accessing the body object of a request which is data transfer object or dto so what is a dto essentially dto is a class that defines the shape of the body object so in order to create a dto inside this user module I'm going to create another folder call dto and then inside it I'm going to create a create user video.ts and inside it I'm going to export a class called create user dto and here we can Define the shape of our body which is sent to this post request so obviously this post request is for creating a user so for example we expect that this body object contains a name which is going to be string an email it's again is going to be string and for example a phone number which again is going to be a string so we expect these three properties from the body object which is sent to this post request so now here we can use our dto object so first of all I'm going to remove the name from the body decorator because we want the whole object and then I'm going to define a parameter for this create function called create user detail and its type is the create user detail that we just defined so now we can for example just return this create user dto from this post request and here I'm going to say name and set it to John and also we're gonna have a email it's going to be for example John at sum.com for example then also we're going to have a phone which is going to be some number for example and if I hit the send request you can see that the dto object is now returned to the client so now if I change the body object for example we remove this phone from the body object and send the request you can see that the body object again is returned to us without any error but what if we want to require the client to send exactly these three properties inside the body of this post request to the server we can tackle this problem with the validation pipe from the nsjs with validation pipes we can validate any data that is sent to our application so in order to use them first of all I'm going to install two packages the class validator and also class Transformer and then I'll go to the create user dto file and here we can now use The Decorator from the class validator package so here we want name to be a string so we can use the decorator is string which comes from the clustered editor so let's import it and for the email we can say is email the Creator and for the phone we can say is number string the equator and then I go to the main.ts file and here after Declaration of the app I'm going to say app dot use Global pipes and inside it I'm going to instantiate a new validation pipe and you can see this validation part is come from the messages slash common and now if I go back to the insomnia and send the post request with the name email but without the phone you can see that the it sends me a bad request error which says that form must be a number string and now if I add the form to this body object and click on this in you can see that the dto is returned to the client without any error so you can see that with the help of validation pipes and class validator you can easily validate the body object of a request which is sent to our application so let me show you another case for example if I add a another property that is not inside the dto for example we'll say something else and set it to a string and click on the send we can see that the something else which is not inside our dto is passed through the validation pipe and then return to the client as part of the response object so in order to remove non-defined properties we can go to the main.ts file and here inside the validation pipe we can pass an object and say white list and set it to true so if I go back to insomnia now and click on this send you can see that it automatically removes the non-defined properties from our dto and they are not allowed to pass through the validation part we can also return an error to the client when he or she provides an extra property into the body of this post request so I go back to the main.ts file and inside the validation pipe I'm going to set for bit no invited list to true and then save this and then go back to insomnia and if I click on this send you can see that it returns us an error which says that the property something else should not exist so as you saw we can easily validate the body object of a request with dtos class validator and also validation pipes and the last thing I want to tell you in this section is that inside our controllers we can also have a patch request or a put request and also a the net request so inside every controller we can have several get requests several post requests patch requests put requests and also the niche Quest and I will talk about them in more details later in this video in this section we are going to create our user service and then use it inside our user controller so a property terminal and say Nest g s which means that we want to generate a service and then name of the service which is user and pass the option dash dash no spec because we don't want it to create for us a unit test file for this user service and as you can see it creates for us a user dot service and also update the user module so here you can see the user Services here inside the user module and it also update the provider's list of the user module and added the user service inside this provider's list so now we can use this user service inside this module now go back to the user.service as you can see it is a user service class and is decorated by the injectable the equator of the ad comes from the initials com so what does that mean injectable before explaining that what injectable means let me create a function inside this user service class so here inside the user service I'm going to create a find one function which takes the ID of the user which is going to be streamed and then it just returns a dummy user object it's ID of this ID which is taken as an as a parameter for this function so now we can go to the user controller and here let's rename this function to find one and then inside this function instead of returning this user object we can call the find one function from the user service but before we have to create an instance of the user service manually but since this user service is decorated with the injectable equator it means that this user service is now a provider so providers inside the industries can be injected to the other classes inside the module scope it sounds a little complicated but let me show you what I mean here here inside the user controller we can define a Constructor and then inside the Constructor we can define a parameter so we're going to say private read only user service which is going to be type of user service which we just have defined and then left the body of the Constructor empty so since the user service is decorated with the injectable decorator we can delegate the creating an instance of this user service to the nest.js runtime so now we can easily access to the user service so inside the find one function we can say return this that user service that find one and then pass the ID to that find one function we don't need to worry about where to create an instance of this user service and how to manage them as I mentioned we delegate this job to the next JS runtime only because this user service is marked with the injectable decorator so here as you can see we didn't instantiate a user service like this for example const user series equals to new user service we don't need to do that because this class as I said is injectable and we can inject it like this into our user controller so I hope that makes sense for you it might be a little complicated but this is what the next year's runtime does for us and we don't have to worry about that so now let me go back to our insomnia and here send a get request to this user slash for example 45 and send it and you can see it returns us a user object with the idl-45 so in this way we can access and use our services inside our controllers and let's create a dummy create function inside our user service so we can create another function for example create which takes the create user dto is going to be type of create user PTO class and then inside it which is return it's on a string that says the user is created just a dummy message for now to see that if the correct method inside this user service is being called so I go back to the user controller and then return this that user service that create method and then pass the create user detail into it and now if I send a post request to the slash user route now we get a bad request says that the property something else should not exist and that's because there's something else property is not existed inside the create user detail if I remove that and click send you can see that the user is created message is returned as response to the client so in this way we can create and use our services inside our modules and one last thing about these Services is that we can use this user service only inside this user module for example if we had another modules for example comment module we couldn't use the user service inside the comment module unless we import the user service inside the providers list of the comment module so let me show you what I mean in action I'm going to create another module comment module so I was a nest the module Chrome lens and then create a service for this module I'm going to say Nest GS and then name of the service which is comment okay I go to the comments module and inside the comment service will create a function called find user comments and then it takes the user ID which is going to be string and it's just return a dummy message for example this is the comments of the user that is a dummy function so we are going to use this comment service and call this find user comments inside the user controller so here for example let's create another get request which is for example slash user slash ID and then slash comments and then create a function for example get user comments and inside it we are going to catch the params which is going to be ID and here we can access to the ID which is going to be string and inside it we are going to call the comment service Dot find user comments so here inside the user controller inside the Constructor we can inject the comment service so we're going to say private read only comments service which is going to be type of comments service okay and here inside this get user comment we can now return this that comment service that find user comments and then pass the ID of the user so it sounds good but if I go to the terminal you can see that it gives us an error which says that Nest can't resolve the dependencies of user controller so that's because we use the common series inside the user controller which is not belonged to this module so in order to fix this problem I go to the user module and inside the providers I'm going to select it also requires the comments Service as the provider and if I save this you can see that the arrow is gone and if I call the users slash user slash ID slash comments in insomnia for example we want the comments of user with the idl-45 and then its comments so let's send the get request to this endpoint and you can see that it Returns the correct message which it says this is the comment of the user which is returned by the find user comments method inside the comment service so in this way we can access to a service inside the controller which these two don't belong to the same module so let me recap what just we have done we just need to go to the user module and inside the providers list of the user module we just have to add the common service that's it so now let's just runtimes knows that we want to use the common service inside the user module and it doesn't give us an error so yeah I think that's it for the services and now we can go and move on to the type RM section in this section we're going to set up a postgres database in a darker container and then configure our sjs app with type program to connect to the postgres database well type program is a powerful object relational mapping library that allows you to easily work with relational databases in your node.js applications although you can use it with mongodb as well and by leveraging the power of type program you can streamline your database interactions and reduce the amount of boilerplate code required to work with your data as first step in this section I'm going to create a Docker compose file in order to set up the postgres database in a darker container so I close the SRC folder here and I go to the root path of our project and here I will create a new file and name it docker Dash compose that yaml and then inside it first of all I'm going to set the version to 3 and then create our services and then the first service is the DBA which is going to be our postgres database and set the image to the postgres and also restart to always and then in the volume section we are going to map this directory inside our postgres container to this DB inside our physical machine so now if I stop the Boost Grace database container in our physical machine the database data will be persisted in this directory inside my physical machine and the next time when we start the postgres database container our database data will be there and then we map the port of 5432 our physical machine to the port of 5432 of the docker container so any request to this port on my physical machine will be redirected to this port of the darker container and then set the environment variable first of all I'm going to define the database name which in this case is going to be just test DB and then say the username for the postgres which is postgres itself and also the password of the user will be postgres so that's it for the postgres database container also I'm going to create another service which is going to be adminer and set the image to the admin or image so admin error is a graphical user interface that you can use with your postgres database and I believe that it is working with all of the relational database systems over there in this video you can see what it is and how we can use that and then map the port of 8080 our physical machine to the port of 8080 of the adminer container so that's it for our Docker compose file and I save this and in order to run this Docker compose file I open up the terminal and inside it I'm going to say sudo docker compose up and I enter my password and you can see now the docker container is up and if I open up our browser and go to localhost 8080 you can see that the adminer container is running and here in the system I'm going to choose the postgres and in This Server I'm going to put DB because here the name of our postgres service is DB and then put the username which is postgres here we Define the postgres's username and also postgres as a password and here I click on the logged in and you can see the test DB is now there and it creates the test to be inside the postgres database for us so in this easy way with the help of Docker compose we have set up the postgres database in a darker container and one thing I want to point out here in order to run the docker compose inside your application be sure that Docker is installed in your machine so now we can go ahead and install type program in our sjs application I go to the documentation of the initials and inside the technique I select the database and here I copy this script for installing the type RM and then go to my vs code open up a new terminal and paste that script here and as you can see this script will install the initials type program the type program itself and also MySQL 2. so my sequel to is the MySQL driver for node.js but as you know here in this project we are using the postgres database so I removed the MySQL driver and then add PG so PG is the postgres driver for the node.js so I hit enter to install these three packages okay now I go to the SRC directory and insert it I'm going to create another directory called entities and in this directory I'm going to create an entity for our user model so I'm going to say user dot entity dot TS and first of all I'm going to export a class named user and then Mark it with the entity decray of that comes from the type program so this entity decorator will mark this class as a model and then type program creates a table inside the database for this model and also we can pass the name of the table for this model inside the entity decorator so we can just say users and it will be the name of the table for this model inside our postgres database or we can just leave it to type over able to choose a name for this model in the next step we are going to create our field for this e-user model first of all it has a ID which is going to be a number and we are going to mark it with the primary generated column so inside our postgres database it will be a primary key and also it will be set to the arrow increment property so every time we create a user object or user entity we don't need to pass the ID for this user model and it will be generated automatically by the database system so the next column that we are going to create for this user model is the name of the user which is going to be streaming and then we mark it with the column and also inside the column we can say that it is going to be unique and for example nullable to false so it can't get a null value inside our database and also we are going to have an email field so I'm going to say email is going to be a string and then Mark it with the column the Cradle from the type program and pass the properties for it and say it it's nullable to false and also unique to true because we want every user has a unique email inside our postgres database um the last thing let's keep it simple we are going to have a password property for this user model and it will be string and also let's mark it with the column the equator and let's pass the novel to false as an option to this decorator and here also we can Define the triggers for the user table inside our database system for example he will want to define a hash password function and every time a user object is going to be inserted into our database system we want this hash password function to be run and HD password that is provided by the user and then save the hashed version of the password into our database system not just the original password that user has provider so for example we can say at before insert and then Define our password function it's going to be async one hash password foreign so by doing this every time a user is going to be inserted into our database system this function will be called and round so here we can say this the password and then hash the user password so before doing that let me install the Big Crypt Library which is used for hashing the password inside our node.js applications so I'm going to say npm I decrypt okay so now we can use the big whip so here in the top of this file we're going to import the Big Crypt so I'm going to say import Star as bigcrypt from big words and then we can use the big groups here to Hash our password so we're going to say decrypt then attach and then pass the user.password we say this the password and then pass the number of the salt or round which I'm gonna pass the 10 because the documentation of the initiates recommend the 10 for this parameter and this hash function is an async function so we're going to have an await before this function and now we can see the arrow is gone so in this way we can create a before insert trigger for this user model and every time a user is going to be inserted into our database this hash password function runs before the insertion of that user okay so far we have successfully created our first entity model with the type program but we haven't yet configured the type RM for our next JS application so to do this I'm going to close the SRC directory and inside the root path of our project I'm going to create another file called ormconfig.ts and then inside it I'm going to create a config object so I'm going to say const config and set its type to postgres connection option and then first of all we specify the type of this connection which is going to be postgres and the database which is going to be test DB because it is the actual name of our database inside the postgres database system and then we pass the host which is going to be localhost and then specify the port number which is going to be 5432 so if I go back to the docker compose file you can see that here we map the port of 543 to our physical machine into the same port of the darker container of postgres database system so we specify this port inside our orm config file and then pass the username our postgres database which is going to be postgres and then specify the password which is going to be again postgres and this is not a good idea to directly pass the username and password of our database system inside this omconfig file because it is not safe and we should put the username and password of our database system into a environment variable file and then read these values from the environment variable file here but for now we go ahead with the easy way and also we have to define the entities so for now we just have defined the user model so here we're going to say user and if we had other entities we would have to add them inside the entities list of this or config file here and for the last step we should set the synchronize property to true so with this property every time we commit a change into one of our models for example adding a column or remove a column will also rename a column the type program will commit these changes into our database system but you should be aware that setting this property to True is very good for the development process but it is very important to set this property to false in the production environment because if we set this synchronized property to true in the production environment we may lose our data so again it is a very good inside the development environment and it's not good for the production environment okay and as a last step let's export this config object from this file and save this and I go to the main module of our application which is app.module.ts file and inside the Imports list let's add the type of our module and then call the for root function and then pass the config object that we just created inside the Orum config file so I import the config from om config file as you can see here and then pass it to the forward function of the type of module inside the Imports list of our app.module.ts file and let's save this and open up our terminal and see if there is any or not as you can see there is not any error so it means that the tar program is working without any error so I go to the adminer and open up the test DB and you can see that the user table is now created in our test DB inside our postgres database system so in this way we can create a entity model inside our postgres database system automatically with the typeform so let me quickly recap what just we have done in this section so far so I go back to vs code first of all we have created our entity with this equator and then we created a warm config file in the root path of our project and we created a config option which its type is the postgres connection option and then pass the type to postgres database Test TV blah blah blah blah and then here inside the entities we have passed user entity model and then we set the synchronize the true and as a last step we went into main module and inside the Imports list we call the type or a module.forward function and then pass the config option that we just created inside the orm config to this function so that's it if it is run without any error which means that it is working and to check that we can go to the adminer and check the test DB and if we see the user it means that it is working without any error so let me open this user table and you can see it has an ID with the r increment property because we marked it with the primary with the primary generated column the Creator so it will be created with the auto increments property inside our postgres database and then we created name email and also a password so that's it for this section and in the next section we are going to create other entity model the comments model and also topic model and set up the relationship between these models okay in this section we are going to create the topic entity model and also the comment entity model and then set up the relationships between these three models so as you can see every user can have multiple comments and every topic can have multiple comments as well but each comment can only have one user and also just one topic so let's do that in type RM so I go back to the vs code and let's close this off and inside the entities directory I'm going to create another entity named topic that entity .ts and then export a class called topic then Mark it with the entity decorator from the turbo ramp and inside it first of all we're gonna have an ID which is going to be number let's stick ready with the primary generated column and also it has a title which is going to be stream and also it has a description which is going to be a string as well and let's decorate these two property with the column equator so the type of room create a column for the title and description in the topic table inside the postgres database okay and let's save this and create our comment model so I'm going to say comments that entity there are TS inside I'm going to export a class name comments and then let's decorate it with the entity liquid from Thai program and then it is going to have an ID which is going to be a number a text which is going to be string and let's stick with the idvt primary generated column and also the text with just column if I go back to the diagram here you can see that the comment has the user and also a topic inside it so here I'm going to say user it is going to be user model and also we have the topic which is going to be topic moral so now we have to set our relationship between the user and Common Table and also comment and topic table so as you can see in the diagram we can see that each comments only can has just one user but each user can has multiple columns so the relationship between these two models user and comment would be many to one many comments can have one user so here inside the comment the relationship would be many to one pronation and then inside we are going to pass a callback function which takes the type and then Returns the model that is existed outside of the relationship which is in this case is the user so the type of other side of the relationship is the user and then pass another callback function which takes the user and then turn user dot comments so comments does not exist in the user model so let's save this and go back to our user entity and here we are going to define a relationship between the user and comment although in many to one relationship is optional to define the relationship on both sides we can just say that user and then user return user.id in its works but if we want the user entity access to its common directly we can Define the relationship in both sides so in the user model entity we're going to say comments which is going to be a list of comments and Define its relationship so every user can have a multiple or many comments so the the relationship on the user side would be one too many so one user can have multiple or many comments so we're going to say at one to many and then pass the type of the other side of the relationship which is comments and then another callback which takes just one comment then it turn the comments there are user so in this way we have defined the relationship on both sides of the relationship so here we can return the user of that comment instead of just returning the user.id so again if we want to define the relationship just on the comment side we should hear return user.i but since we have defined it on the user side we can now refer to the user dot comment so in this way we can have a menu to one relationship in the comment side and also a one tool mini relationship on the user side so let's go back to the comments and Define another mini to one relationship for the atopic property of the comments entity so many comments can have one topic but each topic can have many comments so the relationship on the common side would be minute to one so let's pass the first callback function which is the type callback function which Returns the type of other side of relationship which in this case it would be topic and then pass a topic and then return topic dot comments obviously we didn't Define the comments on the topic side so I go to it topic entity and here we can have a comments which is going to be a list of comments and then Define one to many relationship so each topic can have many comments but each comment can only have one topic so this is the logic behind the one too many relationship and let's pass the type call work function which Returns the other side of the relationship which in this case it would be comments and also let's pass just one comment and then return the comments that topic so now if I go back to the comment section you can see that in the second callback function the topic that comments doesn't have any error so let's save all and open up our terminal to see if there is any error or not so obviously we have a error here so so yeah we have an error here because in the orm config file inside the entities we didn't add the comments and topic models I want to add topic and also comment so if I save this and you can see the error is gone and if I go to the adminer and go back to our test TV let's refresh this let's go to the DB section and select the test DB and you can see here now we have the comment table and also the topic table so if I open up the comments you can see that it has two firing key a user ID and also a topic ID and the target of the user ID is the table user and the target of the topic ID is the table topic so in this simple way we have defined the relationships between these three models also we can have the many too many or one-to-one relationship but I think it is beyond the scope of this crash course and I will later create a full crash course for type RM so you can now subscribe to my channel and hit the Bell button to get informed by this video so now that we have defined our three entities let's use the repository for these entities inside our services so every entities for example a user entity can have a user repository and with that user repository we can search a user or multiple user inside our database create or insert a new user object into our database or update user inside the database delete the user-friendly database and you can do all the crowd operation with repository related to each of our model entities so in order to show how we can use the repository of each entity model for example let's go to the user service and here first of all in order to access to the repository of the user inside the Constructor of the user service let's inject the repository of the user so first of all I'm going to create the Constructor and then put the inject repository decorator from the type program and inject repository which comes from the nest.js slash type program and then pass our HD model which in this case is the user and then just like before all private grid only user repository or just user repo and set its type to the repository and then pass the generic type to the user model entity and then put the body of the Constructor so now we can access to the user repository but the initials gives us an error and that's because if we want to use the user repository we should import it inside the user module or the module that this service belongs to so obviously this service belongs to the user module so here inside the Imports list of this module we're going to add the type over a module and then call the full feature function and inside it we can pass the entity models that we want to use their repository inside this module and in this module we want to use the user repository so we pass the user entity model inside the full feature function of the typorum module so let's add a color here and you can see now the arrow is gone so there's a difference between this type over a module inside our user module and the one that inside our main root module or app module in the app module or our main module we call the forward function and then pass the config object that we have defined the orm config file but in the user module where we want to use the repository of our model we call the full feature function not for root function the root function is for the root module but the four feature function is for our chart module so now you can see the errors gone and let's go back to the user service and here inside the find one method let's remove this dummy return here and now we turn it to an async because it is going to read from the database and obviously it has to be an async function so now we can return wait this the user report as you can see the user report is injected into this class using the Constructor of the user service and here we can access to the user report and then we can call the find one function and then inside it we are going to pass an option object and then it has a where member which is going to another object and inside it you can specify our predicate so in this case we want to find the user based on its ID so we say its ID is going to be this ID which is passed through this method as a parameter so we're gonna error here and that's because we have defined the ID inside the user entity file with the type of number but here we are going to pass this ID parameter with the type of string to this in other words we are going to pass a string type into a number type so in order to fix this we just have to change the type of this ID parameter to number and go to the user controller and also change the type of this ID parameter into number so let's save this and go back to the user service and you can see that the error is gone so let's go back to our service and write our create function so let's remove this dummy return here and turn it to an async method and first of all in order to create a user we have to create a user object and then save it with the user report into our database so let's say const user equals to a weight this the user report that creates and then pass the create user detail create user detail and then we just return weight this that user repo that save and then pass the user object that we just created so in this way we can easily insert a new user object into our database so let's check the create user detail it has a name email phone let's uh remove the phone because in our user model we don't have any phone let's open up the user entity model it has an ID name email and also a password so let's fix the create user video it has a name email and also it has to have a password so let's define the password here it's going to restrain and then let's mark it with the is string decorator here so now it should work and let's go back to our user controller in the create method here we extract the create user D2 from the body and then return the user service dot create function which insert a new user into our database so let's open up the insomnia and let's send a post request into this endpoint slash user name is John email is John at some.com and let's remove the follow and instead add a password and set its value to just one two three and now let's send this post request to our backend database and here we go we can see that it Returns the user object and if you notice here it has an ID of one because it's the first user object inside our user telling the postgres database so it has the ID and also it hash the password from the let's open up the user entity from the before insert and hash password here so let's go to the adminer and open the user table so let's select the user table and you can see that the user with the name of John the same email and also the highest password is inserted into our database that simple and as I mentioned in the beginning of this section guitar program will reduce the amount of one operate code required to work with your data so let's go back to our vs code and go to our user service here and here let's define update function which is going to be in async which takes the update user YouTube it is going to be type of update user detail class but we haven't defined the update user dto class yet so I go to the dto directory and inside this create user detail I want to export another class export class update user detail so the body of this update user detail is exactly as the same of the create user D2 it should have name email and password so it has these three properties but each of this property in the update user dto can be optional so we don't need to define the update user detail from scratch we just have to extend it extend the partial type of the create user dto class so the partial type function comes from the addresses slash map type so you can install it with the npmi at this JS slash map type so now let's go back to our service and import the update user detail and write the body of the update function we're going to say return wait this that user report that update and then pass the ID of the user that we want to update so obviously we have to have an ID parameter here so I'm going to say ID it is going to be a number and then our update user dto so here in the update function of the user repo first we press the ID and then pass the update user D2 just that simple so let's save this and go to the controller user controller and here let's define a put request for these controller so I'm going to say add put and then we are going to have an ID plan and then after that we're going to have an update function which takes the param ID and then let's take this area as parameter and then we're going to have the body the equator which extract the body from the put request and then let's have it update user dto which is going to be type of update user video so now here let's just return this that user service that update and then pass the ID from the prams and then pass the update user detail which is extracted from the body so now let's save this and open up our terminal to see if there is any error so here there is not any error so let's go to the insomnia and here let's change the method of this request to the put and let's pass the ID of the user that we want to update obviously we just have one user so I'm going to use the one for the ID of the user and in the body section we can send the properties that we want to update for example let's remove the email and just send the name and send it to for example circular and let's send the put request to this backend API and as you can see it says that the affected is one so now we know that one row inside our database is affected by this request so now let's go to the adminer and select the user again so as you can see they are the name of the user is now changed to Sakura so now we can remove the name and just send an email which is going to be for example Sakura at sum.com and let's send this as you can see the affected is again is one which means that has been run in the postgres database so let's go back to the admin around again select the user and you can see that the email has been changed inside the postgres database so yeah I think it's enough with the introduction of typorem in sjs but type RM has a lot of more advanced functionalities that explaining all of those functionality requires a complete and comprehensive crash course for type RM itself so my next video is about the authentication in messages and the next video after that will be what the crash course of typorem itself and I will explain all those functionalities that typeform offers in messages so if you have not subscribed to my Channel please subscribe to my channel and hit the Bell button to get informed about my next video so let's go back to the vs code and here as you can see we haven't created the comment module completely and also the topic module creating these modules controller services for comments and topic is exactly the same of the user so in order to make this video shorter I will create all of those services and controller for the carbon module and also topic module and then upload the whole project into the GitHub repository and I will put the GitHub repo of this project in description below of this video so yeah I think that's it for the crash course of niches and I hope you got the fundamentals of the initials so again remember that my next video is about the authentication in messages so stay tuned for my next video and if you like the video please give me a thumbs up bye bye
Info
Channel: Sakura Dev
Views: 24,927
Rating: undefined out of 5
Keywords: nestjs crash course, nestjs, nestjs tutorial, postgres, nestjs microservices, nestjs graphql, nestjs course, nest.js, nestjs typeorm, postgresql, nestjs vs express, nestjs postgres tutorial, nestjs postgresql, postgresql nestjs, nest.js tutorial, nestjs typeorm postgresql, react crash course, full stack crash course, next crash course, nestjs authentication, nestjs/typeorm postgres, nestjs training, nestjs apis
Id: Hv70fn8xTL4
Channel Id: undefined
Length: 70min 42sec (4242 seconds)
Published: Sun Apr 09 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.