Learn NestJS – Complete Course
Key Takeaways
This video provides a comprehensive course on NestJS, covering topics such as setting up a new project, creating controllers and services, using TypeORM for database operations, and implementing authentication and authorization. The course also covers advanced topics such as using Docker and Railway for deployment, and testing with Jest.
Full Transcript
learn the fundamentals of nestjs by building the back end of a Spotify clone nestjs is a framework for building efficient scalable node.js web applications you'll learn how to design a database create rest apis and deploy the apis to production how did Alie develop this course welcome to my course nestjs let's talk about what is nestjs nestjs is used to build server side application in node.js it is built on the top of node.js expressjs and typescript the major difference between nestjs and other nodejs framework is this framework is using typescript and it is using the angular architecture angular Concepts on the pack if you familiar with angular concept you can work with nestjs is very easily why they are using the angular concept because if you use the angular architecture Concept in the back end you can organize your project in a easy way the development would be easy the contribution for other developers would be easy in sjs look at the documentation you will find the controllers providers modules middleware exception filter pipes guards inter interceptors and custom decorators all of these are Concepts in angular why they created nests if you have worked with Express you don't have any structure like you don't have any best practice to organize the backend project so they created the structure architecture level they designed the architecture to build server side applications in nodejs and typescript under the it is using expressjs and typescript so they are just solving the architecture problem when you build the large application in nodejs we backend web application in nodejs when your code base is increasing day by day it's hard to follow specific architecture that's why they have created the nestjs if you follow the nests you will see hey we need a controller we need a provider we need modules we can break application into multiple modules we need a middleware we need exception filters so this is how you can architect your backend application this is exciting project I'm going to share you all of these Concepts in this course let's create a new project in njs first of all you need to install ljs globally on your machine I'm going to install nestjs CLI this this command will help us to generate nests project my CLI has installed now we need to create a new project you can use this command Nest new the name of the project you can choose any name here I just use in fundamentals dpro I'm going to use [Music] npm now it is going to it's going to install all of these packages for me now my project has created successfully so I'm going to navigate to my project directory this is end fundamentals Das Pro now I'm going to open that into my code editor I'm going to use vs code so when you open the package.json file you can run your project in development mode by using this command npm start Dev npm Run start D you can see my project has started successfully uh by default njs uses 3000 Port you can verify that from the main. file I'm going to go to the Local Host call in 3000 let's see what will happen you can see Hello World so our project is running fine now in the app controller you will have a simple message the simple controller method it's a route get hello and you will see the hello world here hello world or you can say hello I'm learning nestjs I saved the application it has reloaded successfully let me send the request again you will see hello I'm learning njs so this is our source folder you will place all of your Source folder source code inside the source folder this is our main.ts file when you run this command npm run Start Da njs is going to call this bootstrap function and inside the bootstrap we have a factory function and we are initializing the app module this is our root module in here we have set the port we have the service we have module controller and the test file for a controller this is our module remember this is the angular structure and each module is consist each module consist of controllers services and providers you can import multiple modules here we have the [Music] service and uh you will place all of your spec file inside the test end to end test should be uh saved here and unit testing you unit testing files will be located here this is eslint RC rules for eslint prettier n if you want to customize the nest C nestjs project you will do inside the nest CLI we have package.json file we have TS config and TS config build this is used for typescript configurations let's talk about the concept of module in njs in njs each module is consist of providers controllers imports and exports so this is the building block of nestjs application you can read my notes I have provided you the PDF documentation nest in providers nestjs are classes that act as a Services factories or repositories if you have worked with angular you know the providers so you can encapsulate your business logic and it can be injected into controller or other services so controller serve as the function of handling HTTP request whenever you create a new endpoint you will register it inside the controller I'll teach you more about controllers in the next video Imports is an array specify the external modules needed for the current module you can import other module let's say you have break down your application e-commerce application into multiple modules you have post module you have products module you have ERS module you have users module let's say a user module can use the product module this is how you think in terms of modules if you want to export you can also export controllers and services from the current modules so each nestjs application will have a root module just like in angular root module serve as the entry point and is responsible for instantiating controllers providers and other core elements nextjs follow the module isolation principle ensuring that application is organized into distinct functional or feature based modules so you will have root module app module let me check the application you will have the app module you can see that you have Imports array this module has app controller and app service let's say we're going to build a back end of Spotify application we can divide our application into multiple modules you will have a root module and I'll have the artist which is feature module and we will have songs module to handle the songs functionality we have o module to handle authentication these three are all the feature modules SS modules are a functional organizational unit that follow the modularization principle it helps to do code free usability and separation of concerns principle under the hood they have implemented the principle design pattern to organize your code that's it let's create a new module I'm going to create a song module you can use CLI Nest G4 generate in the name of the module which is the module keyword I want to generate the SS module here you can provide any name I'm I'm interested in the songs module so you can see in the app. module it has added the entry automatically for you in the Imports array and you can see you have a songs module that's it so this songs module will have controllers providers and imports and exports array controllers are responsible for handling incoming request and sending response back to the client we are building the Spotify clone application let's imagine or let's say you want to fetch all the songs or you want to see all the songs of Martin gck artist your browser will send the find all songs request to the nestjs application inside the nestjs application you will have songs controller inside the songs controller you can see we have find all method the find all method will be called and this method will fetch the songs record from the database and send respon response back to the client similarly you can send the same request from your mobile application so controller will be responsible for handling request and sending response back to the client you can create a controller very easily all you need to do is controller decorator and inside The Decorator you can provide the prefix route prefix if you want to define the request Handler inside the controller you have to use the HTTP get decorator if you want to create the post endpoint you have to use the post decorator it's just returning a simple string message fetch all the songs and this method will be converted into this API endpoint Local Host callon 3000 / songs we are going to build these API endpoints to fetch all the songs to fetch a single song I created these routes to create a new song to update a song on the based on ID and delete a song on the based on [Music] ID I'm using the rest client extension to send the API calls it is similar to The Post men if you don't have rest client you can find from the vs code extensions and find the rest client the rest client package is saying You must have a file with HTTP I created the HTTP extension now my application is running at Port 3000 my development project is running at 30001 you should not aware you should not care about this project we are building project on Port 3000 if I send the request to fetch all the songs we don't have any rout yet it is giving me the warning message or error 44 you don't have all these end points I want you to accept the challenge and start building these end points we don't have any controller let's stop the application and I'm going to create a controller songs you can see that songs controller has created inside the songs folder we have spec file testing file and controller. TS file this is the controller decorator this is the prefix one more thing it has added the end entry in the controllers array now let's create the request Handler first of all I'm going to implement the get find all it is going to return a simple message find all songs let's restart or run the application you can see that our application is running now let's fetch all the songs I got find all the songs find all songs endpoint it means we successfully created the route to fetch all the songs now now I can send the request to fetch the songs watch all songs end point let's create a single song endp point you have to use the ID as a dynamic parameter I can say find one here I can say fetch song on the based on ID similarly we need update put for update I'm going to use the put HTTP verb update update song on the based on ID we also need delete I can get the delete from here let me replace the update to delete delete song on the based on ID and finally we need a post endpoint to create a new song I can say the post create create a new song so we created the CED API end points now it's time to send all the request it's working fine now create a new song endpoint update song on the based on ID delete song on the based on ID now you got the basic understanding of controller and how to create route in njs application let's talk about Services services are providers it means you can inject into another class it will be treated as a dependency we will have a service and the service is responsible for fetching data from the database and saving data to the database if you have to interact with database you have to write the source code inside the service you will create a method to interact with database we will use repositories don't worry and this service can be injected into controllers if you have multiple controllers into module you can inject the same service into that controller or multiple controllers you can also export the service from a current module and you can use that service into another module we will have the song service it's nothing more it's just a class and all you need to do is to injectable decorator it means you can inject as a dependency into another class this is how you will inject the service into controller or into a class you have to inject it in the Constructor it will be treated as a dependency for the songs controller now the songs controller is dependent on song controller is dependent on the song service let's create a new service I'm going to use n CLI to generate a service let's write the name which is songs it will create a class and it will inject into our songs module you can see that we have the song service spec file which is testing file and we have the surver we we have used the injectable decorator one more thing it has registered as a provider inside the songs module I told you services are provider providers could be factories helper function you will learn more about dependency injection in more details in the later mod so I told you service services are responsible to interact with database right now we are not going to interact with database we'll use the postris SQL postris database in the later videos for that here I'm going to create a local DB which it should be array local array saving saving record in the disk private read only songs array I'm going to create the empty array let's define a new method to create a new song and it is going to return let's push the song make sure you get the song from the create method there is a method push and I we need we need to provide a new song and let's create another method find all and and it is going to return a simple array this. songs and I can return this. songs array so we have created two method now it's time to inject this service into the controller I want you to do it accept the challenge and do it all right I'm going to do it for you song service now inside the create I can use the song service by using the this this do song service please create a new song I'm going to provide a dumy name Animals by [Music] Martin you can choose any name don't worry we will create a separate song model and separate interface for the song let's call the return and for the find all I am going to use this do song service. findall let's run the application our application is running let's send the API request to create a new song you can see I got a new song if you sent all the songs request I got all the songs let's save another song you can see I got five songs let's fetch all the songs I got all the songs so our service is working now in the real world application we will write the database code code here here save the song in the database and here what we will do fetch the songs from the DB but we will implement this feature in later videos in this video I'm going to teach you how to validate the request body when you send request to the Local Host call in 3000 3000 SL song we are trying to create a new song but let's say if I miss the title field it is going to give me the validation message the title should not be empty and title must be string let me REM know the artist now you can see title should not be empty and artist should not be empty so I would like to add this validation to our create new song API endpoint when you go to the Spotify if I click on any [Music] song this is the title of the song and this is the published date or release date and this is the duration so we're going to pick title duration and the date of the song let's do it this time I'm going to use class validator let's install the class validator package and we also need class Transformer you can see both packages have installed nexts provide validation pipe you can use validation pipe for specific controller method you can use it here or you can use it here it's your choice but but I'm going to create a global I'm going to register it as a global so I can use in any controller so you can call use method there is a method which is use Global pipes nexts already created the validation pipe you don't need to create it again I have imported the validation P from next sjs common package and now if you don't have dto which is data transfer object you have to specify the network data transfer object properties let's create a new song create a new file create song d. now we need to add decorator paste very adds let's create a new class and I'm going to name it to create song dto the first property is title I'm going to make it read only and we have the second property which is artist array and we have another property which is release dat or you can specify the type which is string and the type of part is it's an array and we have the DAT there is another property which is duration we need to store the duration in the time format now I'm going to use the decorator from class validator the type of title should be string and it's a required property so you can say it's not an empty we can follow the same stuff for artist not empty it's an array it's an array and you can say type string let's add decoration decorator for release date type should be string and class validator provides a decorator is date string now we have for if you want to store the time or add the validation for the time there is a there is a decorator which is military time and it's also required property so I'm going to add is not empty so is date string if you want to apply that you have to add the date in this format and you have to add the time in this format now we're going to apply we have already registered validation pipe here and we created the data transfer object which is create song dto now I would like to apply this create song dto in the create endpoint you can register it or you can apply it by using the body parameter please apply it on the request body and I can say create song create song dto the type is create song dto and this time I'm going to push create song dto let's try to test it out and we need to run the application so we have to send the request or add the Json body in the response let me open the rest c. HTTP file and we need to add the Chason body let's send the request you can see title should not be empty title must be string artist should not be empty and artist must be an array so validations have applied successfully I can say let's say lasting lover the title and we need the artists s let's now we're going to test it out so we have this record if you will add the date in different format you can see dat should be valid ISO 860 date string for date string format if I do in this way you will get the error dur must be valid representation of military time which is hours and minutes so it's working fine now let's talk about the middleware a middleware function runs before executing the route Handler inside the controller songs controller I have the find all route Handler and the create route Handler if you if you want to run any function before executing the route Handler you can write your code inside the middleware it's a function a browser wants to fetch the songs before fetching the songs would you like to call any method would you like to run your logic would you like to execute any type of code middleware can have request object response object and next function it means you can customize the request object if you want to add header if you want to log the request time you can do that a middleware can execute any type of code you can modify the request object if you want to add the request header authentication token to the request you can do in the middleware you can end the request and response cycle you can call the next middleware function by calling the next method we're going to build the logger middleware let's imagine you want to send request from your browser to server before executing the route Handler I would like to log the request message or the DAT time let's implement the logger middleware it's a class we're going to build a class based middleware and to create a middleware you need to implement the nextest middleware interface it provides a use method and use method will have the request response and the next function here I'm just logging the request dat time and at the end I'm also calling the next function it will if you will not call the next function it will not go to the next step one more thing middleware it's is like a dependency you can inject into module it will act as a dependency here we are injecting the middleware as a dependency to inject the middleware as a dependency we need to implement the nest module interface it will provide the configure method and the consumer will be middleware consumer and we just need to call the apply method from the consumer object and you need to provide the logger middleware here you need to specify where do you want to implement the logger middleware I would like to implement for songs API let's implement the locker middleware before creating a middleware I'm going to use Nest CLI please give me the help for nest generate command you can see that I got all the commands related to Nest generate you can generate class controller decorator filter guard middleware pipe provider we also have other options like no flat please do not create directory or no spec please do not create testing file let's create a new folder common I'm going to place all my middle Wares inside the common directory next generate Mi common SL middleware and the name of the middleware which is logger and I don't want a spec file please do not create the directory let's try with no flat and dash dash dry run let's see what will happen dry run it will not create the actual file but got the steps you will get the understanding how it will run it's working fine now no files return to dis but when you EX cute this code it will create the logger middleware file inside the middleware directory that looks good so I'm going to remove the dry run let's write the file perfect we have created the logger middleware you can see that it has already implemented the nest mid middleware interface and I got the use method with these three arguments request response and the next function here you can customize the request object if you want to add your custom logic you can do it here I can say request dot dot dot new date whatever you want to do do to dat string so we created the middleware now I told you or I taught you how to apply the middleware I want you to do it in the app modle we need to implement the nest module you can see that I got the configure method and we need to call consumer. apply the name of our middleware which is logger middleware and we have the four roots or routes I can say the songs now we need to test it out let's run the application my application is running now we need to send the API request if you will send the request to the root URL which is Local Host colum 3000 our middleware function will not run because we applied the logic to songs route fetch all the songs and I got the the log here request log send the post request I got the request log send the put request or send the delete request I got the log there are two other options to implement the or to apply logger middleware I can say option number one consumer. apply logger middleware for routes please run for only songs path and for only run request method. poost it could be option number two if you send request get request to fetch all the songs it will not run if you will send the post request for the songs I got the request if you send the put you will not see the request log another option we have let's do it consumer zor dot apply logger middleware for routes you just need to provide the controller it could be option number three it depends on what use case you like to use now I can fetch all the songs and I got the request log which create a new song I got the request log update a new song and I got the request log this is how you will create a middleware did you think about the error handling in njs if error comes from your application code nestjs provide builtin HTTP ex exception so let's say error comes while fetching the data from DB but we did we did not add any logic to handle the errors gracefully let's imagine we got the error while fetching the data from the DB error in DB while fetching record let's imagine that when error will happen nestjs will send this error to http exception this is the built-in exception in nestjs let me let me send the request to fetch all the songs you will see the server error with 500 status code next s has sent this message from HTTP exception but you can use the exception in your controller functions let's say I can say or did you think about how can you catch the errors you have to use the try catch block I can log a simple message I am in the catch block and this is my error let's try to fetch all the songs you can see that I got the error message I'm in the catch block and this is the error it means we successfully got caught the exception but we want to send the useful method in the useful status code in the response I can not see anything here for that we need to use the HTTP exception I can say through new HTTP exception it's a class and we need to provide the message can say server error or whatever you want to say I can say server error and we have to provide the status code HTTP status provides a lot of status codes you can use anything whatever you want to do for me server error internal server error if you want to send the message or cause which should be the error this one let's try to fetch all the songs you can see that I got the message server error with 500 status code which successfully caught the exception but if you want to use different error message you can do that you can use forbidden status code it will work let's restart the application now I got it so we have the status code 403 instead of 500 I'm going to replace forbidden to internal server error this is how you will cach the exception in your source code if error will come from this service this this method TR cach block will cat the eror got it let's talk about the pipes in njs there are two use cases to use the pipes the first one is to transform the value here in our example application we have the find one method we are expecting the ID as a input parameter by default it is going to give me the string so I can use the parse int pipe to transform the string value to number here you will see the type of ID it should be number another use case for pipes are to validate the input parameter in the create method we will accept the input argument like song title song artist we will validate the all the input arguments by using the validation pipe let's implement this transform value in our demo application so I'm going to remove it let's start it again it is giving me this response in nestjs you get you can get the dynamic parameter by using the ram decorator Ram decorator and the name of our argument which is ID I'm expecting the ID and I use the template string let's define the type of ID I'm going to send the request you can see the type of the ID is string we were expecting the number type but nestjs got us the string type you can convert this string into integer or the number by using the pipe Pars in pipe that's it let's send the request to fetch the song on the based on ID you can see I got the number ID number type if I provide the string value here you will get the validation error validation failed numeric string is expected bad request error if you want to customize the error message you can instantiate it eror status codee HTTP status dot not acceptable now I got not acceptable if I provide the numeric string I got the ID which is number type of the ID is number we successfully transformed the string value to number value in the next video we will implement the input validation using pipe we will create the custom validation pipe you have learned how to inject dependency by using the Constructor based dependency injection pattern we have injected the song service into the song controller what what will happen when songs controller will inject or instantiate the song service let me open that songs controller here we are injecting the dependency song service and we have provided as a dependency here this one this song service when Nest container instantiate the songs controller it first looks for any dependencies in our case we have the song service when it finds the song service dependency Nest will create the instance of the song service and cach it and it will return it if already created the cache then it will return from from the cache it will not create the new instance let's imagine you are using the song service inside the multiple controllers the first controller let's say we have the songs controller I'm using it first time here if I use song service inside the song service dos back file it would be treated as a second time now the second time it will not create any instance it will get the instance of the song service from the cache this is the Singleton pattern applied here next under the hood created a Singleton single instance of the song service and it is going to share the same same single instance throughout our songs module but you're going to learn multiple scope if you want to use the scop scope strategy if you want to instantiate a new instance after for after every incoming request you can use the scops but I'll talk about the scops later there are many techniques to use the providers some of them are standard providers value Prov providers known class based provider tokens class providers we use that class providers Factory providers used Factory providers and nonn service providers we're going to play around with all these six techniques let me explain with the help of examples this is the standard provider inside the S module we are using it as a standard provider but you can convert the above syntax into this one let's use it I need to open my project we need to create a new Branch model 3 lesson number one open the socks module so we are using the standard provider technique but you can write the above syntax or above code by using this syntax I can say this is provider just this it now we have the song service and the song service please use it as a class when you inject it into another class we are using inside the class in injecting as a dependency now you can test the application I'm going to send request to any URL let's create a new song artist must be [Music] stream this is this true why artist I think so I got the issue in the create song d I did add the H should be true I'm telling to class validator the elements of the array type should be string each element of the array should be [Music] string now it will it will be working fine if we have three articles or three artist Martin and John you can see that it's working fine now so we also tested this syntax this is the standard provider but if you like this syntax you can keep this syntax but I just want to show you I'm going to this out uncomment this one now I got the song service now I'm going to talk about the value providers if you want to create the moing service instead of the original service you can do that with the help of use value the use value syntax is useful for injecting a constant value or you want to put an external Library into Nest container or replacing a real implementation with more object we are using this one we are replacing a real implementation of song service with Mo object so when you need this use case you have to use the use value or if you want to inject a constant value you can use the use value or if you want to inject external Library into the nest container you can use the use value let's do [Music] it I'm going to create a mocking object here we have a find all method inside the song service when you open the song service you will see the find all method but we have to return the songs I'm not going to throw the arrow would be song service and use value which is songs moing object Mo song service that is it now now we need to test it I'm going to fetch all the songs and this time you are getting the response from the mo object not original song service so we have the find all method and it is returning this one if I will app add the artist I'm going to fetch all the songs from the mo service object mock service and you can see I got the record from the mock service instead of original song service find all method we have learned how to use the use value now if you want to inject the known class based provider you can do that let's say I want to inject an object with connection we have three properties connection string if you would like to inject any object object as a dependency you can do it well with use value I told you you can inject constant by using use value you can object an you can inject an object or you can inject the working object let's create a new file with connection. file and I'm going to specify some connection properties you have to create an new constant. file inside the common folder and I'm going to add the constants directory here you will have constant. TS [Music] file I can say connection. and I'm going to copy the code I just defined three variables and I have Define the type which is connection now I would like to register it as a provider you can register inside the songs module or you want to register it to app module it depends on you provide this is the name or the token value this is how I will inject in the class when I will inject in the class I'll use this token [Music] key use value let me provide which is [Music] connection so we have to inject it inside the song service I can use the add inject decorator so songs controller I think I injected inside the song service so I'm going to inject here inside the song service or let me inject in the Constructor function here I would like to inject I can say inject let's provide the key private connection here we need to provide the type I have defined the type this is the type so I can log the connection this. connection if you will not add the private so you can add directly without adding the this keyword I did not add the provider so I access the connection string without adding the this so let's say this is I can say I'm going to use the template string this is connection [Music] string when songs controller will be instantiated this Constructor function will be called so it will log this message you can see we have this is the connection string so I can get the connection string now I can see this is connection string and I can say the connection [Music] string or you can say my SQL dot dot col do dot 1 2 3 6 or maybe Port I created the fake or dummy connection stren you have learned how to inject the object as a provider and used it as a dependency now we're going to talk about class based provider we have already used the class based provider here this one not this one this one used Class so I'm going to create a new service this this will be called da config service inside the dep config service I'll have one property and a one function DB host and get DB host remember it's an injectable service so you can register it as a provider inside the app module by using the use class syntax and you have to provide the name of your service in our case we have the da config service and and then and then I can use the dev config service inside the app service so I can create a providers hold up let's rename providers let's create a new class def config service.ts and we have these properties we have TB host in the get TB host so let me register inside the app module we have provider and I can say please provide Dev config service in the use class Dev confli service and and now I can inject inside the app module let me inject it here I can say private Dev config service and I can say def config service and I can call the method from the D config let me convert into the template string da config service. DB host so we have to send the request to the root URL to test it rest let me send the request hello I'm learning NS fundamental and this is the DB host which is St config which is Local Host DB host so if you want to inject the known service provider like a simple object and you want to inject Dynamic value you have added the check or if condition if node development equals to development then you you have to inject the dev config otherwise you have to inject the pro config if if you have two objects and you want to inject on the based on condition this is the known service provider it means these will not be classes if you have this type of use case you can inject by using the use Factory so I'm going to call inside the app module let me let me show the demo I just created the two object and in the provider we have used the key which is config and I use the used Factory and we have to provide the arrow function it's just returning a value Dev config and the pro config if you want to in inject dependency or inject provider only based on condition then you can use the US Factory and now the same way you can inject config value in the app service here we have to inject it by using the inject decorator provide the key which is config in private config we have Port value and type a [Music] string and you can say Port should be this do config do Port so we have to test it to send request to the root URL now I got the host which is Local Host and the port which is 400 so we have to add 4,000 you have learned how to inject provider as in the standard way you have learned the use value you have learned how to add non class based provider you have learned how to use use class provider how to use the dynamic how to in how to register the dynamic provider and finally you have learned how to how to register known service providers the previous video you have learned multiple techniques to register a providers when you register a provider by default nestjs use this scope default it means a single instance will be created which is called the Singleton pattern and this single instance of the provider is is shared across the entire application nextest cach the instance when application request for the second time it will not create a new instance second time it will return from the cash another injection scope technique which is request a new instance of the provider is created exclusively for each incoming request and we have the third technique injection scope technique transient providers are not shared across consumer each consumer that inject a transer provider will provide a new dedicated instance most of the time you need default scope because single turn instance is recommended to improve the performance of your [Music] application when you get the instance from the C it will give you the instance in the more faster way instead of creating the complete object it just give you the copy of the already created object so you can play around with injection Scopes let's say if you want to use it inside the song service I didn't I could not find how to debug the dependency injection so you have to use here [Music] scope injection scope what we have to say scope scope to transient the performance of your application will be hard it will decrease the performance but but it depends on your use case what are your requirements similarly when every incoming request if you have use case you want to create a new instance you can use it well for the requesting purpose for testing purpose I'm going to open the songs controller and here we have to [Music] say it's an object let's import this scope I'm going to send the API request it's working fine one thing you did not notice when I will create a new song it should add the song in the array so I have created three objects three songs object in the songs array when I will send the request to fetch a single song or all songs it should give me the empty response because on every request it will delete it the complete data complete songs because it will also re instantiate the song service inside the song service we we have the are we have the songs are you can see I created the song now when I try to fix all the songs it should give me the first song or all songs you can see the empty response in this video I'm going to teach you how to add one to many or many to one relationship between two entities where a contains multiple instances of B entity and B entity contains only one instance of a entity we have two use cases we are building this Spotify clone if you are using or you use Spotify each user has its own playlist and each playlist can have multiple songs so you as a user can store multiple songs or save multiple songs in the playlist so there is a one to one one to many relationship between playlist entity and the songs entity see similarly we have each user can have multiple playlist many playlist can belong to a single user so this is also a many to one relationship between playlist and the users let's create the playlist entity and add relationship we don't have any playlist entity go ahead and create a playlist entity I have created a new folder playlist. entity. TS file so I'm going to copy couple of the code from my notes we have created the playlist entity now we have to make make a relationship between songs and the users similarly type orm provides one to many decorator and this represents the target entity relation entity we are making a relationship with song entity this representing the inverse side of the relation in the song model we have a playlist property and we have the array of the songs I'm going to copy this code and I'm going to paste it here we don't have song. playlist open the song entity here we can add a relationship but we also going to add a relationship between user so I'm going to copy this code and paste it here now we have to add many to one relationship in the song entity so many songs can belong to a playlist for each unique user we have to import the playlist import many to one relation and finally we have to add one to many relation in inside the song inside the users user entity so I'm going to copy that code inside the user model and I'm going to paste it here now everything is fine now I have added many to one relation in the song it means it will have the primary key of the playlist entity and save it as a reference key or the foreign key now we need to create the clip playlist module I also want [Music] to create a new playlist I'm going to create a new endpoint but first of but first we need to register our new entity I'm saying to type orm please convert or make relation between playlist and the user playlist and the song every everything is fine now when you go to the pg admin refresh your tables you will see playlist table this is the playlist table and we have the user ID when you open playlist entity we have added the many to one relation it means it will have the user ID as a foreign key and inside this song entity we have added many to one relationship as for the playlist so this song will have the primary key as a foreign key of the playlist entity let me show you inside these songs we have a playlist ID relations have created successfully we created one to many and many to one now I want to show you how can you save a record with relation entities go ahead and create a playlist module you can use with n CLI to create a playlist module but I'm going to use my not notes playlists module. and I'm going to paste my playlist module we don't have playlist service and we don't have playlist controller I can create these two files controller. let's create playlist dot service. file I'm going to copy my playlist service we have to import couple of tip dependencies inject dependency and we need playlist we need a user we we need a song that is good right now also need to get the injectable we also need to import report osit Tre I don't have any user so import the user we have service right now and we going to create controller or we can build create playlist function I'm going to create a new method you can see that we don't have create playlist dto we are just creating the instance of playlist I'm providing the name of the playlist when you go to the playlist entity you have the name property each playlist can have multiple songs so I will get IDs of the songs from the request body we are using the same logic in the previous video we used here I'm setting the relation with songs entity I am creating the playlist when you are when you need to create a playlist you have to provide the name and you can set the relation for the songs and you can set the relationship for the user when we will implement the authentication I will not find the user directly from the database I'll get it from the logged in user we have set the relationship with user and finally we are saving the playlist we don't have create playlist D go ahead and create a playlist D we have used that logic I'm going to create a new file playlist dot or you can say it should be new folder dto inside the dto playlist create playlist dto create playlist do D.S we are expecting the name type should be string and I'm getting the IDS of the song from the request body that's why I specified the number type the array of the numbers and we have the user it should be a number it should be the ID and finally we have to use the create playlist dto we have to import it and now we have to build our controller function and the endpoint do we have a controller yes we have a controller everything is good to go I've have specified the playlist with this endpoint we injected the playlist service we have used that logic and I'm returning a simple playlist in the response we have to register the playlist module inside the app module and it will also be treated as a feature module just like we did with songs module we have playlist module now I have to test the application you can test it by sending the request do we have a user I already created the user in the previous video I can double check check it my users you can see that we have three users I would like to save the record for the second user with ID number two rest client we have to create a new playlist I can say create new playlist we have to send the post request Local Host column 3000 playlists content type is equals to Json application Json let's provide the data I'm going to create a new playlist with Feelgood now I would like to save the song with ID number six do we have the song with ID number six let me double check it yes we have the song with ID number six and this is our user let's say I'm going to say I'm going to create with user ID number two it's not a valid request now it looks fine we need to add a space here we have a playlist feel good now and we have a one song with ID number six and we have this user so this user has playlist feel good now and it has only one song you can double check it from the playlist this is the playlist record in this video I'm going to teach you how to connect nestjs application with type orm and post nestjs provide multiple drivers to connect with database if you want to use mongod DB you can also do that if you want to use my if you want to use post you can do that in this video I'm going to implement the post with nestjs uh typ orm is a object relational mapper you will write the code in JavaScript objects and these objects or classes will be converted into database tables if you want to write SQL queries you don't need to write plain SQL cury you can write queries in the form of objects first of all you have to install a couple of dependencies we need nestjs typ orm package and post driver and type orm uh open the package tojson file and you have to install these dependencies I'm going to add them here let me install all of these dependencies we also need typing for nestjs we have to install this package I'm going to install as a def dependency we already have this package types at node we installed these packages njs type orm post and type orm so now we need to import the type orm module into our root module in our case root module is our app module so we have to call this method from type or a module and you have to provide the connection strings or connection properties like type host Port username password database entities and synchronize whenever you will create a new entity you have to register it here for synchronize means whenever I will run the application please delete the data from all the all the tables synchronize please delete everything from the table but do not use synchronize in production otherwise you will lose the production data whenever you have to create a new entity you have to add it here inside the entities array so the for root method Sports all the configuration properties exposed by the data source Constructor from the type or a package I have installed PG admin if you don't have you can install the post admin I'm using PG admin 4 you have to provide your password let's connect with server we have to create a new database right now I'm going to create a new database Spotify clone this is my user go to the app module and we have to import the type type or module here we have have to install manually it's not giving me suggestion from Nest JS type orm and we need to get type omm module so I'm going to call a method type orm module do for root with we have to provide the options database which is Spotify clone host which should be Local Host and we need to specify the port for post gr I think 4 5432 by default username for me it's postcript add you have to provide your password for me I think it's root I specified the database name and we have empty entities right now I don't have any entity and synchronize set to true it will create the database tables po it should be usern name not a user so how can you verify we have successfully connected to type orm you can use data source object in the app module now you can inject it and I can log let's add private you can log anything from DB name let's say and I can get it from the data source dot data source. database this do I have that property let me check it dat source. driver dot database Let's test it out I'm getting the error wrong driver so I think I did not provide the type let's add the type the type of the driver which is post now we have made the connection successfully you can see DB name which is Spotify clone you can also check the songs table inside the Spotify Let me refresh it and I would like to look at the tables we have the tables I don't have any song because we did not create any entity right now but we have successfully connected to the postris database in this lesson I'm going to teach you how to create an entity entity is a class that maps to database table or collection when us using mongodb you can create entity by defining a new class and Mark it with an entity metadata and inside the metadata you can provide the name of the table in our case I'm going to provide the songs table name an ID which is the primary generated column the ID will be generated automatically it's an auto increment and we have the title I use the column decorator for artist array postris also Sports error data type you have to provide the column and I'm using the V character you have to say this column is an array type you have to specify the array should be true and we have a release dat property or release dat field in the database table I'm specifying the call colum decorator and we have and we are seeing this the type of this field which is State we also have time type in the post you can say we have the duration I specified the date data type in the post Cas you can Define the time I don't want to save extra date field here I only need Time Properties time related metadata and lyrics lyrics could be the long text that that's why Post sports text type if you want a long if you want to store a string with long content or long long length entity songs which is the name of the table and you can say I spec I have I I have specified the description for each field when you will create the entity you also need to update the lyrics in the create song datto we did not we did not add lyrics property in the previous videos that's why I use the lyrics it's an optional property it depends on the user does user want to add lyrics or not and finally we need to register the entity to the app module and then you can can test the application let's try to implement it go ahead and create an entity I can say songs or song. entity songs. entity or song whatever you want to call let me say what I called song. entity dots let's specify the class I can say song I can provide the entity the name of the table which is songs now we need primary generated column ID the type should be number and we have the title field let's specify the title [Music] column title type should be string and we have another column this time we have the artist array you have to specify it as a string array here I I can say the V character V character and the type should be aray and we have release date duration release date let's it should be date release date type should be date and we have duration type should be time duration and the date and finally we have the lyrics type should be text lyrics type should be string now we need to test this entity you have to add register the entity in the song in the entities array now it should create the songs table for us let me test it out from the PG admin refresh the tables I got the songs table with these columns ID title artist release date and the duration we don't have any [Music] record so let's update the create song dto and I'm going to copy it and I'm going to paste it here create song dto let's add another field the optional which is lyrics everything is fine now we have tested it in the next video you are going to learn how to perform C operation we're going to fill these methods update delete find one find all and the create this time we going to fetch and save data to the database let's perform cred operations type orm Sports repository pattern for each entity type orm provides repository and this repository has CR features like create create record update record find record and delete record repository provides the method first of all you have to register the type or a module as a feature into the songs module we providing the entity like these entities I would like to use inside the songs module and it it will provide the repository songs repository here then you can inject the songs repository to use songs repository you need to import the type or a module into songs module just like we did it here this this module uses the four feature method to Define which repositories are registered in the current scope we only need song entity that's why we use the we have imported or added the song entity now we can inject the songs repository into the song service just like we did we did it as a dependency injection please inject the song's repository and the type of the entity which is song and you can in you can import repository from nestjs type or M package now I told you songs repository provides scrud method to create delete update here you can look at that create delete fetch records from the songs table let's implement this create song method this time we don't need to add a record in the local DB you're going to save the new song by using the song repository. save method let's Implement here in the songs module we have to import type orm module as a feature provide the song entity I would like to use this entity into the songs model in songs module now you you are able to inject songs repository into the song service so I want you to inject this songs repository Constructor pattern songs Repository repository and I can provide the song type which is entity now you have the exess of crud methods so song repository provides this safe method just like you learned here it provides this safe method for first of all we have to create a new song and it should return a promise with song so I just created should say create song dto the type should be create Song D so I just created the instance from a song class I specified the title I got the title from D I got the artist from dto duration lyrics and release date from the dto and finally you can call Safe method this. songs repository and I will would like to call this safe method and provide a newly created song and it should return the object get rid of the songs array I don't want to use it we also need to remove everything from here now it's time to test this G method make sure you have called yeah it should use the up expression here in the controller let's look at issue here it should promise and the song inject the repository inject repository and we we have to provide the entity which is song so everything is fine you can test without a sync V by default it should return the promise HTTP let's create a new song we also need lyrics I'm going to send the request amazing we have a song you can verify from the database you can see that that I got the first record this is the lyrics duration and the release date now it's time to implement find all it's easy to implement the find all all you need to do is provide the return type promise with song array return this do songs repository do find that's all you [Music] need and in the controller songs controller you can also add promise with song aray let's fetch all the songs from the DB I got the array right now we have only one record now we need to implement the find one find by ID you can create a new method inside the song service and it is taking the ID as a parameter and returning the promise with song you can use song repository. point1 method and in the controller we need we need to pass the ID as a integer and return the song in the response let me open the songs controller we already did it I'm getting the ID all you need to do is return this. song. find1 here I can say promise with song Let's test it out by sending the request only the based on ID you can see I got the first record if I try to fetch the second record I don't have any record that's why I got the empty let's implement the remove method I'm going to create a new method inside the song service it's just returning nothing or you can say delete result you can use that and return here and we need to use this method into the songs control ER we have to call it this Do song service. remot and we have to provide the ID we did not pass the ID or get the ID as a Prem I'm going to use Prem decorator and get it here ID and it's returning promise with delayed result we need to test it out first of all let's create a new song to we have a song lasting lever two the ID of the song which is two now you can perform the delete operation I would like to delete this record so I got the delete result we have successfully deleted if I try to fetch all the songs [Music] no I think I deleted with ID number one so first record has deleted and we need to use the update let's perform the update record so we need update method I'm going to create a new method inside the song service we don't have update DTU data transfer object you need a tip you need a new data transfer object for update the record because when you update the record all the fields are optional but I can get update result from type orm we don't have update song dto we have to create it I'm going to create in the dto update song Das d. so this time we have to copy everything all the fields are optional all I did I copied the create Song D and put the optional for every title for every field is title should be optional so I can say instead of empty it should be optional it should also cre it here is optional is optional now it looks good so we have to use the updates s video now we need to implement the controller function songs. controller that we need to get the Prem and we need to get the body need to get the pram and update song dto and I'm going to call this do song service. update the first one is ID and the second argument is update song tto you have to import it the return type should be promise with update result that's it I have found the issue which is this space content type let's try to send the update request duration must be valid presentation now it looks good so you can double check it from the database this is the record with id2 we have successfully updated the record we have tested the application in the next next lesson you will learn how how to implement the pagination now we're going to implement the pagination I'm going to use external package to implement pagination in nestjs uh first of all you have to install this package I'm going to register it here and we have to install it and now I'm going to add a new method inside the song service this time I'm going to call it paginate and I'll use paginate method from nestjs type or M paginate and it will accept the pagination options like page metadata when you will fetch the record on the pation it should give me the items array and we have this metadata total items item count items per page total pages and current page these are all the options inside the options object and finally it will return the pation and we have to provide our model which is song and we have to call the page unit with song entity we have to provide the songs repository and the options if you need to add a cury builder like filtering or sorting you can also do that but here is our control rer function we use the Prem now we're going to use security decorator and it should name of the field which is Page you can add a by default default value which is one and I applied the pars int and I have added the default value and we have another field or another property and I'm getting it from the cury prams this is the limit and default limit which is 10 and I applyed the pars into pipe operator and finally it should return the pagination with song entity if limit is greater than 100 please do it 100 otherwise we have to specify the limit or tell or add the limit there is a page unit method we created inside the song service and you have to provide the page and the limit we're getting the page and limit from the cury so you have to test it by sending the cury parameter page which is two and the limit whiches to I want to see two records per page and I want to see the page number two if you want to add the Sorting you can also do that by using the query Builder please apply sorting on release date I want to see the latest song on the based on date let's implement it or you can Implement by your own first step we have to create a new method paginate and we need these options I can import all of these from the method so we have the pagate method now we have to call it inside the songs controller you can it depends on your use case but I I'm going to call the paginate method in the find all so I'm going to replace my find all method to this find all we also need cury Prem it's just getting the es lint warning messages we also need default value pipe we need pagination from nestjs that looks good we can test it this time I'm going to send the request to fetch all the songs it has applied the limit 10 and default value which is page which is one over the first page total items item count items per page 10 and total Pages we have one and current page which is one let's add another record new song to let's add another record new song 3 let's add another record new song four now we have four songs you can say I want to see the page number one this time I want to set the limit to two I want to see only two records per page we have the items array you can see we have only two records there are total two pages we are on the first page and items per page two item count two total items we have the four I told you if you want to add sorting you can also do that by using the query Builder inside the song service I'm going to add curil fer here and we have to provide cury Builder not songs repository we have to fix it cury Builder let's provide the cury Builder please create a new song with let's say a new Five song latest date it should should give this record first let's create it created a new song I got a latest song Only the based on release date it means it's working fine now in this video I'm going to teach you how to build one toone relationship between two models one to one relation where a entity contains only one instance of B and B contains only one instance of a let's take an example a user can become an artist or an artist can have only single user profile so there is a one toone relationship between user and the artist we don't have an artist model or artist entity first of all you got to create artist entity with primary key and then you have to create the user entity because we're going to make one to one relationship between artist and the user I'm going to have ID field or First Column first name column last name column email column and the password column for user entity now we're going to add one to one relationship type or provides one to one decorator to add relationship between two two entities uh in the first argument you specify the relation type I'm telling type orm I would like to make a relationship with with user enti this is the type of the relation you specify the relation entity type by following this syntax AR function and this join column will rep will create the reference key or a foreign key of the user entity inside the artist entity so we have so we will have a user ID as a foreign key inside the artist and finally you have to register the user and artist entity in the app module now we're going to implement these steps let's create the first a new Branch so I'm going to create a new artist entity if you like you can use CLI command to generate a new entity so I'm going to say artist do entity. file I'm going to copy my code there is nothing here you already learned how to create an entity and next we have to create a user model a user entity go ahead and create a new folder with user or users let's keep it to artist so I'm going to create a new entity user. entity. P the code we have ID field first name last name email and the password and now we're going to make a one to one relationship I would like to store the user ID inside the artist model if you want to store artist ID inside the user you can also do that it depends on your use case like I want to make a relationship here let me do it here we need one to one decorator specify the type of relationship by following the syntax we would like to make a relationship with user and here we will have the user and the user and I also need a join column that's it for now cannot find a module user. .ts file so we have to import it manually now it looks good and now we have to register these entities inside the app module we created couple of new entities please convert these entities into tables I can say artist and we have user our last step is to test the application and I have to run my PG admin let me connect with post this database so it has successfully let me check my schema which is 45 clone I have to connect it inside the tables we have the artist and the users table we have have the user ID inside the artist and inside the users we have for columns or ID first name last name email and the password our application is running fine now this is how you will make one toone relationship between two entities now we're going to talk about how to implement many to many relationship ship many to many relationship is a relation where a contains multiple instances of B entity and B entity contains multiple instances of a let's take an example many artists can publish many songs and multiple artist can belong to one song or multiple artist can publish multiple songs we have a multiple many to many relationship inside the artist nestjs or type orm provides many to many decorator this will specify the target relation entity and this is the inverse side of the relationship and it will have the songs array and on the song we will have the artist array we have a many to many decorator the target entity in the song we have Target entity which is artist and the second argument specify the inverse side of the relationship inside the artist we have songs property that's why I can access the artist. songs and inside the artist entity we have song. artist that's why I can access the artist from this song entity song. artist that is the inverse side of the relation when you set the casc to true it means you can create or update the record while creating a new song or an artist I'll teach you the benefits of ask getting when you implement the many to many relationship you you need a joint table many to many imple uh relationship always work with third table which should be joint table and I rename it to songs artist and this songs artist will have primary key of the song and the primary key of the Artist as a foreign key and we also need to refactor some create song dto instead of using EST string EST string we going to we are going to get IDs from the request parameter IDs of the artist and IDs of the artist in the update song video and then you have to register the artist entity in the songs module that's because I want to the artist repository inside the songs modle and finally you need to refactor the create method we're going to get artist here the first step we are going to get this artist IDs from the request object or request parameter or the request body and then we will find all the artist only based on IDs and finally here we are going to set the song do artist equals to artist if you have set the casket to true just like we have done it done it here cascading we set to true now it will set the relationship between songs and the artist it will automatically create the record with third table which is the joint table here here it will create a record it create records in the songs artist table by by setting the relation with this one songs. song do artist should be artist and finally we're going to save the song in the using song repository and you can test the application now um let's implement it first so we have many to many relationship I'm going to add this relationship in inser the artist I'm going to do it here this specify the target relation type and we don't have we we did not create the song. artist inside the song entity now we have the songs array let's import many to many I'm also going to implement it here many to many decorator the target entity in our case it's an artist and it's going to take the artist let's specify the inverse side of the relation artist dot songs and we will have join table I'm going to name it to songs artist or artist song let's take it the songs artist and finally I'm going to specify the artist array duplicate identify yeah I don't need this type because I'm not getting the string array from the artist instead of I'm getting the array of the artist from the request parameter we added many to many relationship inside the song model or song entity and we forgot to set the cascading to True here you can do it inside here G SC to true now we need to refactor the create song dto I have to refactor from it should be number and the first argument is an empty and and it looks good similarly we have to refactor the update song dtoo it should be number array of numbers the first argument is empty looks good now we need to register the artist entity inside the songs module so we can access the artist repository inside the song service I I'm saying to type orm I would like to access the artist repository inside the songs module or the song service that's why I have to register it here and finally we need to refactor create song I can say create uh inside the song service so you can do it too if you want here we have to find all the artists on The based on ID then we have to set the relation with artist and songs so you can do it but first of all we have to inject the Repository which is artist I can say private artist repository and repository I can say artist let's get all the artist you have to add a Sync here this do song artist repository find by IDs I can use that method provide the artist ID from the song dto artist now I can set the relation with song. artist it should be artist so we have set the cascading it will create a relation many to many relation with songs and the artist now it's time to test our application rest client here we have to send the post instead of artist we need to send the IDS of the artist a user can become the artist so we don't have any record in the artist and the user model you have to create it manually so I'm going to refresh you can see we have the third table which is songs artsts is not artist we have to fix it inside this inside the songs entity here we have to fix it this I'm going to refresh the table get it off this table you can drop it delete or drop yes now we have song artist with song ID as a foreign key of the song model artist ID we don't have any user right now I want you to create it manually let me do that I'm going to add a new record with ID one it should be Jane or saga Saga gmail.com I'm going to add anything here pass password let's add another user I can say Jane and I can say do Jan at gmail.com password 1 2 3 4 5 now you can save the record so we have two users right now if you want you can also add another user or artist I can say Martin gar Martin at gmail.com 1 2 3 4 5 let me save the record so these two users are the artists but we need to make a relation inside the artist table let's add a new record with ID and here we have to add a artist ID let me double check it yes one and the three one we have to add another artist one the ID should be three so these two are the artist ID should be here we have to set the ID should be two now it looks good so what I'm saying that a user with ID3 is an artist a user with ID one is also an artist so one Martin and seag are an artist and Jane is a just a simple user so when you create a new record I can say let's add a new song so these two are all the artist they are going to create they have created a new song I can say you for me that is it right now I'm going to send the request sounds good we have a new record title this is the artist ID this is the complete artist so we have an art ID one and we have the relationship let me double check it from the artist and the songs it just created a single record it did not get the ID 1 and three I don't know what is wrong with it let's do it here one and three you for me to again I am getting the ID only one let's log the song d. artist 1 and three then what why 1 and three it looks good maybe the issue with here console.log so when you look at the artist record oh we have one and the two so one and the two instead of 1 and three let's provide the two you and for me three now I got the artist ID one and the two it will also addit a relationship here inside the songs and the artist I'm going to find now you can see that a song ID with 10 has two artist these two users user ID number three and user ID number one in this video you're going to learn how to implement this signup functionality a user can create an account in our application and we need to save the user in the database first of all we have to install dependencies I'm going to use bcrypt JS password bcrypt JS package to save the user password in encrypted format I don't want to save the password in plain text like 1 2 3 4 5 we have to save the password in encrypted format that's why you have to install this dependencies let me open my package.json file I'm going to add a new entry let me copy it and I'm going to paste paste it here we also needed to install the typing for typescript I have to add the typing in the dep dependency I'm going to put it here so I'm going to run npm install please install dependencies for me you can see two packages have installed added new two packages now we have to create a user module and the Au module we don't have a user module and Au module inside our application I'm going to use nest CLI to generate a new module I can say o we have created a new o module you can see that we also need to generate the ser service for art you can see that Au service has generated we also need controller I can say AU an au controller has created it has also added the entry inside the controller's part we have it has automatically imported Au module inside my app module here is the O module now we have to create the users module one more thing we did not export the odd service yet here I I can say I would like to export the Au service it means whenever you will import the Au module into another module like we have imported the Au module into app module it means I can inject the OD service inside the app module that is why I exported the OD service let's create the user module I'm going to create manually users. module. TS I paste it we don't have user service yet we have to create the user service let's use the nli a user service has created we have to import the users module inside the app module so we have the user service and we have the user module I've also added the type or a module and registered the user entity because I would like to use the users repository inside my users module I would like to inject the user users repository into the user service now we have to register a new route inside the O controller we're going to register the signup and the login route inside the O controller we don't have a user dto yet but we do not we also don't have a user service do create method I want you to create the user D you first I can say I would like to add my DS inside the dto folder create user. dto file I'm going to paste my code we are expecting the first name last name email and the password from Network request this is the network data request object now we got to create the create function inside the user service it is saving the user inside the database do we have a user entity now we got to do it inside the user service here we have to add the logic we need to inject the user repository I've already told you how can you do it I have created the create method what this create method is doing remember we have installed bcrypt JS package let's import it first I don't want to copy the code inside the Constructor function now it looks good we have to import it first create BPT package here we are just injecting the user repository we are generating Assa it is nothing more it's just a number we need a salt to encrypt the user password there is a hash method inside the bcrypt library and we are using this hash method it is going to return the promise first you first argument would be PL text password we are getting the plain text password from the network request and this is our salt and finally we are just saving the user depository user inside the repository and we are deleting the password it's an extra remove them I don't want to send the user password in the response that's why I have deleted deleted the user password and finally we are returning the user from the response in the in the response we have called the user service. create method here now it's time to test the application one more thing we have to refactor a little bit our users entity I'm going to make it to Unique should be true because because email should be unique for each user and I don't want to save the pass I I don't want to send the password in the in the response it is saying that when working with type orm there might be cases where you want to exclude one or multiple columns field from being selected that's why we have used the exlode now let's run our application and we have to save the user we're going to send this request HTTP we have to send request to this route because we created this odd /up route we have to provide first name last name email and the password now we're going to test it out I have caught the error if user service is a provider if user service is a provider it is is it the part of au module you should learn from the error inside the Au module we have to import the user module because I am using the user service inside my o controller or inside the a service let say user module here we are injecting the user service inside the O controller everything is good to go right now we have to test our application what I would like to send the signup request let's create a new account I got the error 500 internal error duplicate key value Violet unique key do we have a user inside our database can say John one two still we are getting the same value same error cury failed error duplicate Cube value viate constraint we have changed a data entity and the table we have to we have changed the database Act I have added two new entries unique constraint and the exclude so we need to drop our schema and let me do it I cannot drop we did not use migrations at the end of this module I'll show you how to use the migration whenever you need to update a database you have to create a new migration what I want to [Music] do I want to disconnect from the database Spotify clone now I would like to delete it is used by some other let's use another database I can say one I found this is the shortcut to handle this error because we did not use migration so I can say that now I got the data from scratch where application is running fine now let's sign up you can see that it has resolved the issue the issue was with database update I got a user when you go to the Spotify clone one get rid of this one Spotify clone one and we have to go to the tables inside the users we have a de cord email john1 12@gmail.com and this is the password in encrypted format in this lesson you are going to learn how to perform login request when user sent the login request we have to verify the user from our database we have to decrypt the user password and compare the user password we're going to implement Json web token authentication a user provides the credential like username and password to the server then our server will generate the Json web token and send back to the user it will have the header payload and signature don't worry I'll teach you everything when client reive the Json web token if you are building front-end web application you can save the Json web token in the local storage when user want to receive or user wants to receive protected rout he must need to provide JWT token in the request header and server will receive the JWT to token from the request header and it will verify or validate the token if token validated successfully it will allow you to access the protected route you will learn how we are going to implement Json web token authentication we're going to use passport passport strategy or passwort package you have to install these two packages I'm going to install it in my dependencies we have to run npm let me hold on we did not create a separate Branch module number six lesson number two [Music] now we have it npm install we have installed two packages the next step we have to create a login route I can create inside my o controller let's create a new login route we don't have a login D yet we also don't have a login function inside the OD service yet let's create a login function inside the OD service au. service here we have to create the log function and we also need to get user service as a dependency let's create a new method first of all we are trying to find the user on the based on email if user found it should give me this user let's complete this step first we have to find the user we did not create the find one method I can say that inside the user service let's create a find one method it is going to take the partial as a user and we're getting the email or we can let's try to use the login dto login dto if it did not find the user it should return the unauthorized access we have to find the user only based on email we don't have login dto let's create a login dto inside the AU dtos I can create login. D.S file so we have the login dto I got the email we also need to import login dto we also need to import user entity and it should return the user that's it now the second step is we have to compare the user password inside the OD service the second step we have to compare the user password I have to import the bcrypt import Star as bcrypt from bcrypt now I can compare the password with plain text password and user encrypted password if password matched then we have to return the user and delete the user password if password did not match we have to send unauthorized exception that is it right now we did not inject private Au service now I have called the dto login method and provided the login dto let's try to send the login request rest client. HTTP we have created a user with John 12 John 12 run the application let's send the API request to login user it should be 3,000 not a 3,000 one we successfully got the user back in the response let's say I'm going to provide the invalid email I got error cannot find user if I provide the invalid password I got password did not match and unauthorized it's working fine now but our goal is to send the Json web token when user made successfully login request it should send the Json web token in the response in the next lesson I'll teach you how to create Json web token and how to send the Json web token in the response we have found the user on the based on email and we have encrypted the user password if user has logged in successfully we need to send the Json web token and when you will apply authentication on protected route you have to send the Json web token in the header we're going to use nestjs JWT package and passport JWT package and then we will import Port jwd module you have to provide a unique key you have learned how to create the login function and we you have to refactor it right now you have to send the access token you can create Json web token by using JWT service this is the provider you can inject it here as a service provider then I will move my constants into a separate file au. constants does and you have to register the JWT module and update o constant Secrets I also updated the expiry date of Json web token it will be expired after 1 day we going to have JWT service we are extending it from the passport strategy remember I'm using the nestjs passport package and we have passport jwd strategy here it is just extracting the token from the header we are checking the Json web token expiry date or expiry validation or expire duration here you have to provide your secret key which we have saved and then finally we're going to have validate method it is returning the user ID and the email when you apply the oard oard JWT oard will call this validate function you have to register the JWT as a provider then this is how you will Implement authentication you got to create a guard it's like a middleware in expressjs if you want to implement role based authentication you need guards we have jwd odard it is extending oard from the passport if you want to add your own custom logic you can do it here this is how you will make your route protected by using the gwd O card and finally you have to apply you have to send the authentication request like first of all you got a login login route will give you the Json web token then you can access your protected route like this is the protected route profile is the protected route only authenticated user can access this profile route so you have to provide the validation token which is this one Json web token in the authorization barrier it's a scheme and it will allow you to access the route so let's implement it first first of all we have to install a couple of dependencies here passport JWT nestjs JWT and passport JWT strategy I also need dep dependency which is typing of typescript let's do it here and we have to install the dependencies these packages have installed now you are able to use JWT module let's use inside the app module we have to register it we will move this constant into separate file but right now I'm going to do it in this way JWT module. register and this is the secret key and finally we have to refactor our OD service if everything is fine then we can use Au or JWT service you have to add this return type return type if password mashed generate adjacent web token or create a pad object I'm going to create a payload object now we are just adding email and the user ID inside the payload and it is generating the Json web token let's create a separate file for the constants can say o/c constants do let me refactor it here one more thing you got to register the JWT module in the Au module instead of app module that was a mistake so this is our authentication [Music] module we have to register it here out constants do Secret and you have to provide sign in options options we have expiry date which is one day so we have registered the jwd module now you have to create jwd strategy I can say JWT strategy dos it's nothing more it's a service or provider you can inject it injectable export class JWT strategy passport strategy it is going to provide the strategy passport JWT now we have to call Super Constructor and you can extract the header from Au header as a barrier token and we have to provide the ignore expiration check the expiry date secret which is our secret key ke and we will have the validate function whenever you apply at the O card this validate method will be called our next step is to register GWT strategy in the O module I have to register it here JWT strategy now you have to create the guard which is JWT guard dos export class JWT guard it is also a class or service provider that's why I I'm using the injectable and we have to extend it from the passport from the odard which is from the the njs passport package make sure you say this is the JWT if you want to extend this JWT guard you can do this our final step is to apply the O card to the public public route let's say I want to protect this route I did not create it yet let's say get profile and it is going to take request return request. user should be decorator now we have to let's do it without card npm Run start f our application is running now let's send the login request you will receive the access token I'm going to copy it and I going to paste it here access token now let's access the profile slash profile because we created the profile route in app controller I'm going to send the request cannot access the profile I do not add the route I can access the profile route I got the 200 status code it means route is working fine if I apply the authentication guard I can say use roles or use roles use guards yep I can mention my guard which is or guard if you have what in Express JS it's nothing more it's like a middleware this oard function will run before executing the get profile function this function runs before request Handler which is get profile oh it should be jwd o guard jwd guard not and this not this one o card let's rename it to JWT o guard not a JWT guard JWT oard it looks good let's try to access the profile route status 401 which means you did not provide the access token please provide the access token if you want to access this private route so you can provide the exess token by using this format I pasted the token awesome I got the user ID and the email I have applied the OD card and this JWT strategy method will be called first they are going to run the Constructor and then they are going to use the validate function in this lesson I'm going to teach you how to implement role-based authentication what is role-based authentication if your application has multiple roles like artist manager user accountant CFO person you can have a different functionalities for each role in Spotify clone when you look at the Spotify clone only artist can upload a song If you are a user like let me show you you with the help of Spotify web. Spotify like if I go to my profile I don't have any feature to upload a song Only approved artic can upload the song or delete the song in this way you can divide your application into multiple roles we have create songs endpoint I would like to restrict this endpoint for other users only artists should access this create song endpoint we don't have artist module we have to create artist module then we're going to implement the artist module into import the artist module into app module we have to write a method find artist on the B on user ID then we got to add a logic here inside the login method we will save the artist ID in the payload object and then you have to create a new payload type and finally you need JWT artist card we will have a separate card for artist we are extending the jw2 remember I told you if you want to customize or add a logic in the guard you can do that it's just returning a super Constructor and here we are using the handle request method this function will check if you have art artist if you are an artist then it is going to return the user otherwise it will throw the exception we have to refactor the validate method in GWT strategy we need an artist ID then here you will have to apply JWT artist guard on the create song endpoint you can do that as well or you can follow me let me implement it let's create the artist module here we have the artist module it has already imported into my app module this one the artist module we also need R service next generate service and I can say artist you have to import type orm artist entity module. for feature because I would like to use repository here artist repository we have to provide the Artist as an entity so we have the artist service and we also need artist controller artist I can use a nest generate controller artist now we have the artist controller now we're going to create the find artist method I'm going to copy my code inside the artist service let's do it here we need to import couple of dependencies we have to find the artist on the based on user ID our next step is to refactor the login method inside the art service we have to add R service injected we need to add a artist ID inside the payload type inside the payload if password matched find if user is an artist then we need to add the artist ID into the payload what I can say because course I can save the artist ID in the payload object user do p. artist ID should be it is saying that you don't have artist ID in the payload you can create a payload type inside the types p. type I can say types. yes now I can access it I can Define the P type it should be user ID we have mentioned the artist ID is an optional property now we need to have JWT oard I told you how can you implement it we already implemented the O card let's say I'm going to create a new guard inside the O I can say artist JWT godts export class artist JWT guard extends o guard JWT it's a Pur it's a service that's why I have to use the injectable it's a service provider if I will write the can activate you can see that I got the code all I need to call the super Constructor super do can activate and provide the context yep everything is fine you also have handle request now you can write your logic here if there is an error or there is a no user then you have to throw the unauthorized [Music] exception if everything is good to go you have to return the user if there is an artist ID then we should return the user get rid of the extra arguments I'm not using them when you apply the artist JWT card it should call the handle request and it will extract the user and try to check the artist ID from the user if you want to log the user you can also do that I will show you what will happen inside the user we created the JWT AR card JWT o card jwd arst card then we have to refactor a little bit validate method in the JWT strategy we can add the artist it should be P type now it looks good we have the user ID p. email and p. artist ID and finally we have to apply the jwd artist card on your protected endpoint in our case we have the songs create endpoint we have to protect it for other users all you need to apply JWT artist card and inside the songs controller I can restrict this endpoint from other users I can say that jwd artist JWT C if you want to log in the request you can do that let's try to do it here request decorator and request I think it should be request it's not a requ request this one request nexts commment and then we have to access the request why it's giving me the error I have to do it here and request now it looks good I can log request. user let's start the application I got the error the O JWT strategy JWT strategy what I did wrong oops forgot to add I forgot to add closing parenthesis if you go to the artist table you will not see any record because we don't have any artist record it's an empty if you go to the users how many users we have I have only single user now I would like to make the artist what I can say what is wrong is au module is a valid njs module Artist Artist service I think we have to import the artist module here inside the are we using the rst service yes we are using the RT service that is why I need to import the artist module and inside the artist module I can say I have to export artist service I want to teach you how to handle errors you must know you must familiar with error handling our application is running now first of all we have to create a new artist I can say let's sign up a new user or I can say that sign up artist let's say that it should be let's say c Martin Garrick Martin Garrick we have registered a user which which should be which could be an artist so if you want to make this user Martin Garrick to artist you have to update it manually but I did not create the endpoint but you can do that I taught you how to do it let's first of all the ID is to I'm going to open all the artist and we have to add the entry this is user number two and finally you have to save it now Martin is an artist so I have to log in as in Martin gar I can say sign up artist or login artist get rid of first name and the last name let's send the login request it should be [Music] login I got the token now if you check the profile it should have the artist ID you can see that this is the artist ID this is the user ID this is the artist ID from the artist table this one so it's working fine now when you have to create I for I got I I have to get the token again let's save the [Music] token the token will be deleted after one day I can say that arst token temporary if I try to create create a new song it should give me the unauthorized because you are not an artist and you did not provide the authorization token authorization b e a r a r e r now I can say we have artist which is one Mart Martin Garrick has an animal song let's say they want to publish this song I have the artist now it's working fine this is the user ID email and the artist ID user ID email and the artist ID so we got this one artist and the ID colon one we have successfully created the endpoint I can say request. user let's create a new song from Martin Garrick say love again so this is the request. user user ID email and the artist ID in this lesson I'm going to teach you how to use or how to enable how to create two Factor authentication you're going to learn how to implement two Factor authentication if you don't know about two Factor authentication you can read this text a user enters the username and password on a login page page after successful initi initial authentication the system sends you the onetime password or onetime token for the verification a user may provide the onetime code generated by the authenticator app and send to the system then system validate this token if token has validated then you are able to authenticate then you are able to access the route we're going to use third party package to implement two Factor authentication Speak Easy and we need a typing first of all I would like to show you the demo how two Factor authentication works I already implemented in my development project I can show you the demo first of all you got to log to the user I got the access token we're going to create a new endpoint to enable the authentication this endpoint will enable the authentication for the user and it will create a secret key let me show you I'm going to provide this text I provided the token now I got this secret key and I got this response from the Speak Easy package base 32 I saved this base 32 string to my database table for the user is for the user table a user has this record now I I I got this secret key if you have authenticator app Google Authenticator you can you can place the secret key I have enabled the Google Chrome extension I want you to do it when you look at Chrome Google Authenticator you have to enable this extension now I got this authenticator if you have Google Authenticator on your phone or you can install it all you need to do is to add a new app you can also generate the QR code with this OTP path Ot Ot paath OTP o URL you can generate QR Code by using this this URL but you can add manual entry for T testing Sam profile this is the same user the name of the user this is the secret key now I started getting a unique onetime password so I have to copy this password let me do it again it's going to be removed after 1 minute I copied it it's going to be removed yep now I have to provide this token to validate the user I have Pro I'm going to provide it here we also need to have updated token so copy this one and I have to validate the [Music] token yes we have to add a new token because it will be expired now you can see you are verified the token has validated now this user has enabled the two Factor authentication if you send the login request you see this message hey you have enabled two Factor authentication you can implement this Logic on your front end application please send the token at this URL please send the onetime password token from your Google Authenticator app on the front end side you can send request to this endpoint and provide the token that's a complete flow of two Factor Authentication let's start implementing two Factor authentication we have to install couple of packages we need a Speak Easy package we will use this package to generate secret key or validate the token onetime password we also need typing add it as a def dependency let's run npm install packages have installed the first step you have to add two new columns inside the user entity do entity I'm going to add them here by default two factor string should be null and it's a Boolean property by default I have set to default to false two Factor secret could be empty and this is the Boolean value when you run the application it should create two new columns for the user property for the user table our application is running now let's refresh the user table I have the 2 FAA secret and enable 2 FAA which is a Boolean column now we're going to create a new method inside the O service to enable the two Factor authentication first of all we need maybe we need a type I can add my type here enable to F type or you can create an interface we have to type and then we need a method you have to create a new method to find the user on the based on user ID if user has already enabled to factor authentication we have to return the secret key if user did not enable the 2 FAA authentication then we have to generate the secret key this is we use the secret key and we're going to use the base 32 secret key and finally we have to update the 2fa secret 2fa key for the specific user and then you have to write the do you have to return the secret key in the response we got to find the user if user already enabled the secret two Factor authentication we have to return the saved to to f secret otherwise we have to generate a new secret and then you have to set this secret for the user user and finally you have to update the user I'm going to copy the code let's do [Music] everything inside the OD service I have to create a new method import Speak Easy we also need to import Toof enable type we don't have a method find by ID do we have a method find by ID inside the user service not we have to create the find by ID method you can also do the secret key or unable to factor authentication here use user dot let me first add a new method inside the user service let's go to our next step user service here we need this method I'm going to copy this method now we have defin by ID it is going to accept the ID so we have to provide the user ID you can enable two Factor Authentication to true and finally you can call user. Save method or no we need a repository to save it we also need another method it will update the secret key and enable the authentication you can create a new method inside the user service let me import the update results we have completed the enable to factor authentication now it's time to test it let's create an O endpoint inside the O controller I I'm going to use the guard JWT o guard if you if you don't need anybody you can create it as a get end point I can say that JW the O card [Music] I just imported missing Imports we have a login user sign up user sign up artist login user here I can say enable two Factor authentication profile Au enable two Factor authentication let me double check that enable to fa we also need to provide the authorization token so we need to get get the token I got the the access token provide it here let's send the request I got the secret key that's amazing what is the name of the user which is John if you have Google Authenticator on your phone you can install it manually I'm going to add a new profiles which is John user add your secret key it is generating onetime password for 1 minute only we have also saved the key into the user users table let's fetch all the US [Music] users here we have the secret key and it has enabled two Factor authentication our next step is to validate the onetime password token let me open it we have created a new user or registered a new user in the Google authenticator it is generating onetime password we have to take this token or onetime password and try to validate with our application we're going to implement this logic first of all you may you may need another endpoint validate to fa we are also using a JWT o card we are getting the request here we will have a method validated to f a token it is going to provide the user ID the logged in user ID and we also need to get the token valid validate token dto we will create validate token dto I'm going to create a new endpoint inside the O controller I created the post because we need to get the token you can also use the get and get the token prams JWT oard let's create the validate token dto inside the dto I can have validate token. D.S now we have to create a new method to validate to fa token here we need to create this method it is going to accept the user ID the token the onetime password like this one this one this one and we will find the user on the based on ID and then we have to get this secret key which we saved earlier and then you have to provide the token and we have to mention encoding which is based 32 if token is verified where is that if token is verified then we have to return verified to True otherwise we have to return verified to false you can also rapar code inside the TR catch block I'm going to copy my complete code and I'm going to paste it here inside the OD service the code is complete self-explanatory now we have to test it we already created the route inside the rest client I can use that and I'm going to paste it here I can say validate to a token validate to fa let me double check my controller validate to fa it's a post end point point and we have to app content type application Json let's provide the token let me get the token John user amazing we got got the verifi to true if I provide the invalid token I got the verifi to false I got the verified false because because token has expired there is a new token we successfully enabled two Factor authentication validated with token you can add you can also add disabled authentication logic or you can have this feature let's implement it by creating a new function inside the OD service it's nothing more just disable the authentication and or set this value we need to have that function inside the user service because we have repository inside the user service I can say that so we have this method disabled to fa now it's time to create a new route to disable the authentication inside the O controller I'm going to create a new Endo here JWT o there is a typo here spelling issue for the O guard J WD o guard e everything is fixed now let's try to send disable authentication request inside the Au controller this is the get endpoint I can have that let me paste it here disable authentication disable to fa it should be disable not an enable so it has disabled authentication you can double check it by login I got the token and let me check it from my DB you can see that it has dis enable false set the false one more thing you can do if you disabled the authentication you can delete the secret key or you can use the existing secret key let me let me do it yeah we have to disable or deleted the key inside the disable validate token disabled I can say to FS secret to set to false or you can set the null value let's try to do the null value let's enable the authentication I got the secret double check it from the DB we have enabled and we have a different secret key I don't want to save the I don't want to change the secret key you should not change the secret key maybe it depends on your use case if client disabl this to fa maybe he has to scan the QR code again let's disable it it looks good we have empty to fa and it has set to false I also have to add this property into my notes if user has enabled to factor authentication we have to customize a little bit Logic for the login method we have to send the link to user this one validate to F token this one if user has enabled to fa and have the secret key then you have to return this type go to the login or service go to the login method here I can add a logic we have to add return type new return type this [Music] one let's try to access the login function by sending the login request we have enable two Factor authentication it should give you the link not an access token we have to log in the user where is the login user here we [Music] have let's double check it we have empty2 FAA that's why I got the access token let's enable it we enabled the two Factor authentication let's send the login now I got the link validate to fa please send the one onetime password or token from your Google Authenticator app you can implement this Logic on the front end on front end you can send the request to this URL and you have to provide the token a user user has to provide the token so we have completed the two Factor Authentication in this lesson you're going to learn how to implement API key authentication each user will have its own API Keys when he wants to access authenticated route or protected route he has to provide the API Keys when you need to control the number of calls made to your API you can check from your API Keys how many times API Keys has hit if you want to identify the usage patterns in your API traffic you can do with the help of API Keys API key authentication is typically used in scenarios where multiple users or application need to access an API you can read this text you can read the complete flow we're going to use this step we're going to generate API Keys we can create and store API key for each user we have to create an API key strategy strategy service just like we did for the JWT strategy and we have to register API key strategy in a module and the step number five validate the user by API key and apply API key authentication on protected route I have to use external package which is uu ID to generate API key and we will have API key column in the user entity and then when we have to create a new user what you have to do you got to set the API key which is U ID by calling this method it will generate a unique key when you send the when you create a new account it should give you this API key and Next Step you have to create API key strategy when you provide the API key it is going to call this method the validate function and inside the validate you have to call validate user by API key and you have to provide your API key if user is validated this is how you will provide the API key authorization barrier this is my API key we're going to use external package passport HTTP barrier to apply this strategy to validate API Keys finally you have to register as a provider API key strategy this is our method to validate the user on the based on API key if user validated with the help of API key this is our Endo here I'm I can say I want to access the profile on the based on API key or you can create in the O controller use guard o guard you have to provide the barrier it means I want to apply API key valid ation or API key authentication on this route and I don't want to set the send the user back password back in the response that's why I deleted the user password and you can send the message authenticated with API key this is the user this is how you will provide the API key when you make the authenticated request I want you to implement this complete flow if you stuck you can follow my video Let's install the package first let's run the application you will get the error because we have two to three records in users table but it will find null value for API key we did not set the constraint API key should be null if user has signed up we can have the API key or if if you set the null Lael to true you can have a separate function to create the API key for the user it depends on your use case your company or your business logic I'm expecting the null value error from the type orm we are using this database we have all the [Music] users you can see I got the eror relation user contains null value which is API key you can fix two or three ways you can set API key value manually but I don't have API key column there is a concept we didn't use the migration but I found the hack to use to resolve this issue I can say Spotify clone 2 let's change the database Run start there it will take some time to create all the tables database does not exist let's create a DB restart the application the application is running fine now [Music] we have this database Spotify clone 2 so we have the API key now we need to add the API key when you create a new account I can do it inside the user service or odd service do we have the sign up function [Music] here I think inside the users yes we have the create [Music] function I have to change a little bit logic I did not create a new user so I'm going to do it here we have to import this package we are getting the user. password delete this one we got it we got the API key yeah I can say saved password I have updated user D to user password and we have saved the password and we have deleted the saved password now we can we have to test it by sending this sign up request open the r client I'm going to send the request sign up request sign up user so it has generated the API key it looks good we have encrypted password it's fine now our next step is to create API key [Music] strategy we have to install this package I'm going to copy the same code and create a new file API key strategy inside the O API Das key Dash strategy. DS strategy. DS going to copy the code we are using the passport strategy and we are providing this passport HTTP barrier OD strategy we have to import or provide API key strategy inside the O module register it API key strategy and we have to validate the user on the based on API key I can create a new method I also need to find user on the based on API key let's add a new method inside the user service now it looks good let's create a new controller function into the O controller it means I'm telling to a or nests application I would like to validate this route on the based on API Key njs password everything is good to go right now we have to test the application run the [Music] application first of all we have to create a new account I change the email John 13 we got the API key I'm going to store the API key key John 13 now we have to provide this API key to access the profile route access profile we have a get end point get http or/ profile authorization basic here we have to provide the API [Music] key it's not a basic we are using this [Music] scheme barrier scheme b e a r e r now I got the user back in the response and it has authenticated with API key in this lesson I'm going to teach you how to debug nestjs application using VSS code if you don't have launch. Json file in vs code folder you can create it let's create the launch. jsn file if you go to the debug I'm going to create a new folder vs code and you can have launch. Json file let me copy these configurations so I have to start the application in debug mode nestjs has a script in package Chon file now you can start the application by running npm start Run start debug you can see that our debugger has started now I want you to attach a process when you go to the debug now you have to attach it you can put break points let me to here the O [Music] controller I'm going to put breakpoint let's try to send the API request it has stopped at this break point so I can see what is inside the request I have request body request client request. user you can also watch on a specific property the request. user you can see that I got the API key email enable to fa to fa secret this is a great way to debug the application you can find errors very easily by using debugging if you want to debug the complete flow you can do that into the app strategy what I was API API key strategy or API strategy yep we have the API key strategy I'm going to put break point here let me put the break point here and I would like to put the break point here let's send the request you you can see that it has first called this validate method it is going to find the user on the based on API key it has found the user now it is going to return execute this line return user it has now it has added the request. user you have returned API user from the API key strategy like this one nestjs has stored user inside the request object like request. user like this one and finally we have deleted it you can step over it go to the next line if you need to step into a specific function you have to use this one step in if you want to go out from this function you can press step out in this lesson I'm going to teach you the concept of migration migrations is like a Version Control for your database you can manage your database changes by using migrations migration is a file that contains a set of instructions for creating modifying or deleting database tables whenever you make changes in your entity you have to create a new migration if you want to go back to the previous changes there is a command for revert you can use that command once you get into the production right now we are building our application in development environment when we push the application into production you will set the synchronize to false so you have to manually update the changes to for your entities that's why I have set the synchronized to false in production you will not set the synchronized property to True migration is just a file with SQL queries to update database and apply new changes to an existing database I got the simple definition of migration it's called it's like a Version Control for your database you will keep keep track of your changes toward your schema first of all you have to move type orm configuration into a separate file these are all my type type orm configurations now you don't need to write your entities manually when you have to create a new entity you add a new entry for the entity now you don't need that I have added the regular expression for this path we also using the JavaScript because we're going to use migration I found it's easier to work with JavaScript when you are working with with migrations when you build the project nestjs will generate the disc folder this disc folder I can provide that path this is the JS file we're going to provide this type of file I have set this synchronized to false we have created a new data source when you write the script to migrate in package or Json file you have to provide the data source file this this data source and this data source has a data source object this data source object step number two you have to refactor type or M config into app module you got to provide data source options this dat data source options and then you have to write the script for type or M generate run and revert we're going to use all these scripts we will add a new column in the user entity and then we will run run the generate the migration based on this column this is the name of the migration at user phone where we have St about the migration here we have specified the path there is a DB folder and inside the DB we have migrations directory and finally you will run the migration when after creating the file you have to run the migration if you want you can implement this complete steps or you can follow me I'm going to create a new file inside the DB create a new folder inside the root directory DB data source. TS I'm going to paste this code my database is which is Spotify clone Spotify clone 2 so I have to delete everything here we have to provide a data source options this options object I have completed this step number two now we need to add couple of scripts there is no logic logic here specifically you can copy the scripts first of all please build the project generate the JavaScript files then and then we are using the type orm npx and dashd I'm telling to type orm I have stored my database configuration inside this file if if you have to go back or revert the changes you will run this command I'm going to copy this script and paste it here inside the scripts now let's try to add a new column user. entity I'm going to add a new column here here type A String now finally we have to run the migrations npm run migration generate I'm using this script here you are specifying I have I want to store migration in this file migrations and this is the name of the file it will also add the timestamp first it is going to build the project then it is going to execute this command meanwhile I have to start it from the scratch I don't want existing database so I would like to delete Del my database I'm also going to delete this one because we have set this synchronized to false we have to add changes manually that's why we are using migrations and new file has created inside the DB inside the migrations we have this file this is a Tim stamp and the name of the file add user phone. so we have to create a new database I can say Spotify clone now I want to add all this stuff like inside the data source Spotify clone let's generate the migrations I can say that my migrations you can choose any name or in it it is going to take all these entities and creating creating the SQL files SQL queries for all these entities because right now our database is empty in we don't have tables now you can see my migrations if you check the database you will not see any table because we did not run the migration yet now we going to run the migration npm run migration run now it is going to execute these queries these creating all the tables and all the relationships we have the migrations there is no record inside the migrations I'm going to delete this migrations and this migration file let's create it from scratch it has created all the migration now we have to run it everything is good right now it has executed the queries and now if I refresh my tables you will see all the tables we have songs users but if I go to the users I will have font property I don't want font property let's edit a user entity I'm going to remove phone now let's generate the migration I can say removed phone you can see that it has created the migration file removed phone it is going to drop this column now we need to run this migration to update changes in the database let's try to check the column there is no phone column here this is how the migrations work this lesson I'm going to teach you the concept of data seeding data seting is a process of populating a database with an initial set of data when you create a new column inside here when you create a new column in the user entity let's say I would like to add a new column and here I can say this is this could be the phone number but when you run the migrations the phone number will be empty in the database so you can load your initial data by running the seeds applying CED data to database refers to the process of inserting initial data into the database usually when the database is first created let me show you the demo of cing you are going to learn how to create the seed service and we have a seed method inside the seed service we are running type orm queries by using transaction here we have placed all my C data when my application bootstrap loads it will create a new user a fake user and it will save into the database and then it will create the artist and save artist into the user into the database we also have a c data for playlist first of all we're going to create a new user then we're going to create a new playlist and we have assigned a relation between playlist and the user so we're going to save couple of data when you run the application when application will be completed you can verify from your database let me show you in your users table you will see a new user will be created so these are all the users these are all the users I created with fake data by using the seaing I also have a playlist it is going to pick the random name for a playlist Rap playlist World playlist or country playlist I've also have a seed for artist you can see that now my application is is running now when you look at the users you will see another users couple of another users if you look at the playlist you will find one more playlist you can also look at the artist you will have more artist this is how you can increase your development workflow or testing workflow now I want you to implement it by looking at the documentation I created for you here I don't want a new column first of all we have to install another package to generate the fake data and next step we have to create a seeds folder inside the DB seeds I can data seed. TS file I have created a new file while here we're going to do initial seaing you can create a separate function for each entity like you can create a separate function for seed songs I did not create this seed songs method here you can create that if you want to look up more documentation of of Faker package you can find from your from the official documentation page it is giving me the error entities Source playlist here I can find the entity now our next step is to create a new seed module I'm going to use type orm to create a new seed module and then what we are doing here we are generating the encrypted password I use the same password for each user here we are creating the user I got uu ID from API key and I got repository from the manager we will call the seed data in main.ts file seed module has created we also need a seed service what I can do I'm going to copy this code and create a new service inside the seed module see do service if you want you can use CLI to generate service we also have to import or register as a provider seed service cannot find um oh it should be SE data seat should be I can say this seat data seat data and it should be gone we are making connection with our database here I got the manager from the quy manager and I called this C data and finally we are we have started the transaction if transaction if any query has failed it is going to roll back the transaction so our final step you can read this text if you want to learn more about what is cury Runner what is transaction here you have to boot you have to call the seed method here whenever you want to save a data in the database if you don't want to save a new fake data you can just disable these two lines but let me show you the demo I'm going to start the application it is going to run these methods seed user it is going to create a new fake user seed artist and Seed playlist let me show you the current look of my schema I'm using spotify clone on database Let me refresh my tables uh I would like to see all the users there is nothing here I don't have any user you can create many users if you want you can use fake package to generate 20 15 50 55 records and you can and then you can provide into the repository user repository it will create all these records but I use a single record I just want to show you the process you can manipulate with your own use case one more thing I could not find the official package or official documentation or in typ orm seeding I got I have implemented my own strategy now my application is running you can see I have couple of new users you can see I have couple of new artist I think I will have only single artist yes but if you look at the users it has picked a random first name random random last name random last name and the email and the password and the API key it has generated one more thing if you want to look at the playlist I will also have a one playlist electronic music song that's how the seeding work works whenever you create a new entity I would recommend you to create a seed function whenever you run the application it is it is going to create a new data but I'm going to comment this code you can enable the seaing here if you want to make it more Super productive you can create a console command in njs I'll teach you in the advanced Concept in this lesson I'm going to teach you the concept of configurations we're going to create custom configur ation file with the help of nestjs config if you see our main. file I have mentioned the port number manually if you want to have a separate port for development project or for production environment you can specify in the environment variable we don't have any EnV file in if you have worked with nodejs you will have separate EnV environment file. EnV file for development and you you will have separate. EnV file for production one more thing if you look at our type orm configurations here we have type orm configurations I have specified a username manually password manually database manually I also specify the host manually what if you want a different environment variables for production let's say you want to deply the project to AWS or Hoku you need a separate en andv environment variables for production level but we did not Implement that logic now we need to do it if want to read what is configuration you can read this complete text I have explained configurations you may need a database setting for in for development and production you may have different API keys for production and API keys for development you can have multiple environment files for production production and testing nestjs provide provide config module we're going to use this package I'm going to copy it and I'm going to paste in my dependency section or if you want to install manually you can do that I have to do npm install in The Next Step you have to import config module in the app module this config module will have config service and we're going to use the config service to access the environment variables let me show you how can we do it package has installed now we need to import config module into the app module geted of these extra dependencies we have to import it here let's import config module so here we have config [Music] module after importing config module you have to provide the path of your EnV file here you have to provide the path we don't have any EnV file go to your root directory and create two files the first one for env. development for production level I can say en EnV for production this one is for development and this one is for production if you want to have a separate port for different environment you can do that but I'm going to keep with 3,000 for production you can place it here so we have created the EnV file so how can you load this EnV file we have to set the path in the app module here I have to provide the options configurations I can say EnV file path it can access the array the first one is do env. development and do EnV do production one more thing I would like to mention we have used the config module inside the config module config module is using do EnV package if you Google the envv this package is used to define environment variables for different environments for development and per for production but by default nestjs config package is using the EnV we have used this load ENB property so what you have to make it Global let's say I would like to import EnV module into my Au module into the artist module let's say I want to use API keys from env. development file to artist module you don't need to import config module you can use config service automatically but if you use if you make a global when you want to use config module in other modules you will need to import it as it standard with any Nest module or you can make it Global I have set it to Global so I can use config service without importing the config module now we have to create the custom configuration file you have to create a new folder inside the source folder I can say config let's create the configurations here you have to place all your configuration you have to define configuration inside the EnV file and this configuration dots file is is going to fetch or add validations for environment variables inside the configuration so config module is going to use this configuration .s file it is going to to extract all these values from config does let me show you how we have to load our configuration file custom configuration file I can say load you can have multiple configuration file you can have different configuration file for database you can have different configuration file for app settings or user profile settings something like that but I'm going to keep it simple let's use a simple configuration file we have to import the configuration now our next step is to test the EnV variable we have created the port and we have defined or getting the port from uhv and here now let's say if you want to access this port variable I'm going to do it for testing purpose don't do it in production inside the O service let's say I can define a new Vari new function get EnV variable you can call any function here here how can you use the configuration dots file while how can you get the this port into your a service like we have to inject the config service we have to inject the con config service config service remember I did not import the config module into the Au module because we have set it to Global in the app module so we can use config service config service. get pass it into as a integer you have to provide the name of your key which is Port when you open the configuration. ES file we have specified the key which is Port so how can you use this function let's say I'm going to create a controller function for testing don't do it in production I just want to show you the demo I can say test get EnV or you can say test EnV variable it is going to return this do out service calling the get EnV variable that's it do not do any fancy stuff here let's start the application and we have to test this route now we need to test it I have to send the request to this URL this endpoint we have to send the get request can say test EnV 3000 sl/ test amazing I got the Port Port value which is 3,000 it's working fine now now if you check the main.ts file we have defined the port into configuration we are using the port value manually I would like to use the config service here I want to get the Value Port value from the config service and I would like to use it here this is how you can do it you can get the config service instance from the by calling the app.get method and providing the instance providing the config service class it is going to give me the instance config service then I can use the method here so you can do it here config service you can import it now I can get the port value service. getet let's pass it as a number here I can say the port which is key get rid off this no I'm not using seed service we have our application is running fine now let's send the test test request test I got the port 3000 we successfully configured the port in the main.ts file now we also need to add our secret key inside the EnV file we are using getting the value from the Au constants but I don't want to get it from the Au constants I would like to add secret key inside my EnV file I have to place it here secret now I would like to use this secret we are using this secret inser the app module inser the Au module not app module here we are using the O constant. secret but I want to get it from the config service I want you to think about it how can you add or how can you get the value from config service we also need to add a property in the configuration I'm going to do it here and this is how you will get the value from config service we have to register this module as a async and and it is going to return the dynamic module so you have to follow this pattern if you want to configure Dynamic module Dynamic module is a feature that allows you to dynamically configure and register modules at runtime based on Dynamic conditions so we have this Dynamic value so what I want you also have to inject the config service you have to import the config module this use Factory is used to inject the config service and we are getting the value here so I'm going to copy that I'm going to replace my Au module with this code import config service and config module Imports I don't want to use the O constant get rid of the Hat we have to import config module we also need to import config service that is it now we have specified The Secret inside the configuration did I Define the secret in the production I think I did not if you want you can do it env. production let's restart the server our application is running successfully it means we successfully configured the secret key you can test it by sending the API request I have to open it here rest client I can send this signup request it's oh I got I sent the login request we have to send the signup request user has created successfully it's working fine now now our next step is to configure the DB configurations database configuration I'm going to add the configurations inside the my EnV file development file if you want to add a separate EnV file separate configuration for database you can do it can say that DB configuration my database is end test now we have to define the values inside the configuration. ES file I'm going to copy the same code or I need these values now we have to update or refactor the manual values with configuration config service so I I'm going to create a new type orm async config object and then we're going to use inside our type orm module let's refactor it you have to create it this is the same process you have to create this module or register this module as a dynamic I'm going to use the same configuration when defining the type or a module I'm going to do it here you can import type orm config options we also need to get config module and config service type or module options I got the DB host DB Port username DB name password entities and synchronize set to false here we are going to get it from the process.env I'm going to copy that code and I'm going to paste or you can say replace this text host inside the app module we have to register it type orm module this time type orm ASN config get rid of data source wrong driver I think something is [Music] missing postgress we have to use the for root async in the app module I think that is why it is showing me the error you can see that application is running fine now it means we have successfully configured the database we have successfully configured the settings it's working fine now in the previous video we have created the environment variables we have set up the DB configuration DB Port username password and database name we if you want to add the validation if you want to validate these environment variables you can also do that with the help of class validator package to implement the validation you have to create the env. env. validation. TS file we did not add node EnV inside the development or production. EnV I have set the Isam which is enum here I have defined the validation for Port DB host username password DB name and the secret we're going to use class based validator class validator package that's why I created the class and we will have the validate method it is going to accept the config object with record key value pair first of all we're going to use plane to instance from class Transformer package plain instance converts a plain literal object to class based Constructor object you can learn more about class Transformer by looking at the doc so class Transformer allows you to transform plain object to some instance of a class you can look at the documentation of class Transformer if you want to learn more about it and you have to enable this property to true and we have to provide the environment variable which we have created the class this one environment variables and we have the config SE config object you I'll teach you I'll show you what is inside the validated config now it should be the instance of a class if error comes you can send the error back otherwise you have to return the validated config and then you have to provide this validate method inside the config module we don't have node EnV you can create inside the environment variable let me do that first env. environment I'm going to copy that in the production I'm going to copy here now you have to create a new file inside the root directory env. validation. TS file file we will have the enum for development environment it could be development production test and provision now you have to create a class to validate the environment variables we have Port dbhost username password and the secret now we have to implement the logic for validate function it should return the validated object validated config so I got the instance of the class we provided the environment variables here let's say if I would like to log the config I can say please log the config and here I would like to say please log validated config now we have to perform the validation there is a validate sync method you can use it let me import them I'm going to import them here if error comes we need to throw the error otherwise we need to return the validated object validated config object so we created the validate function now it's time to register it inside the app module I'm going to register it in the config module here there is a validate we have to import the validate you have to import it manually it's not giving me the suggestions can say validate from it should not be EnV it should [Music] be env. validation that's why I'm not getting the suggestion because this is a typescript file it's not an environment file now I should get the suggestion for validate let me import it from env. validation do not import it from the class validator package I would like to test this application you can see that we have I have the config object inside the the config object I have the property Port secret node EnV DB host we Define these properties inside the environment file. env. development I got the DB name all these couple of things now you have environment variable which is the instance of a Class A Class based object in environment variables I got all this port all this stuff I'm going to comment this out what if I set the wrong value in the development file let's let me test it if I set the DB Port should be string let's say that it should give me the error I have to restart the application because I have made changes in theb do development file I did not set the validation for DB Port that's why I did not get the error let's say I'm going to do it here DB Port I can say the type should be number I have saved the application I have to restart it you can see that I got the error property DB Port has filed the following constraints is number let's replace the DB Port we have successfully implemented the validations for environment variables in this lesson I'm going to teach you how to increase the speed of module reloading what do I mean by module hot reloading if I change anything here in any file it will take too much time time to reload the application if I'm going to log something here now my application is running first time it will take some time let me show you the problem and what problem we're going to solve and how we going to solve that problem e for in this lesson I'm going to teach you how to increase the speed of nestjs project reloading if I make changes in any file let's say I'm going to delete this code it will take some time to reload the application I would like to increase this speed with the help of web pack you can see that it's taking too much time to reload application nestjs provides a way to increase the speed of your hot reloading you can see that it's still calculating the changes it's still calculating waiting for the file changes I think it has took 30 seconds to load the application let's increase the speed with the help of weback first of all you have to create a new file web H hot modu reloading doc config you have to create this file inside the root directory and I'm going to copy this code because I'm not not going to teach you weac in this course and step number two we have to make some changes in bootstrap function I can open the bootstrap function in the main. file we have to add the code here if module. H then you going to do this process it is asking me which module I going to talk about let me check it from my project yes I need to declare module as a variable I can I would like to declare it here I can also add that part into my documentation now our third step is to add a script to use web pack instead of default configuration to run the project in development mode we have to refactor the start dep script I would like to change it and let's do it this time we're going to run the project with web pack e cannot find run script weback plug-in do we need to install it oh yeah we need to install it e make sure you installed it as a Dev dependency so I need to uninstall it now we need to install it as a dep dependency let's run the project weback is building your sources project is completed let's try to send the API request but it's still running first time it will take some time to initiate the project now project has completed it's time to send the API request I'm going to send API request to root URL let's say I would like to make some changes I can say hello world I saved the application now you can see that it took 2 to 3 seconds to reload the application updated modules you can see that it also loged the message updated modules so I'm going to move this line application has started again I found it's very helpful when you are building a project in development environment we're going to use Swagger package to document the apis if you don't know about Swagger it's an OP Source software Frameworks that enables developer to document and design the restful web services it provides a set of tools and specification for defining the structure end points and data models of an API we will have Swagger specification Swagger editor and Swagger UI if you haven't looked at the Swagger let me show you the demo this is the example of swagger documentation you will have all the end points what these end points are doing you can look at as you can see that we have profile route we have all these routes available you can also create a section for each each route I'll teach you how to do that so I just want to show you this is the overall view of swagger documentation so we have to implement it first of all you have to install a third party package which is nestjs Swagger uh Swagger Nest has created this package let's install this package or I can add into my package.json file let's install it Swagger package has installed now we need to configure this Swagger module in bootstrap function you have to do it here you can use document Builder from a Swagger module you can have to set the title title should be Spotify GL the name of your application and you can write the description for your application you can set the version and finally you got to call the build function and then we will create the document with the help of swagger module and you have to provide your application instance and this config module this config setting and here we're going to mount the Swagger document at/ API route and you have to provide the application instance and your document I'm going to copy the same code and I'm going to place it here inside the bootstrap function you got to do it here let's import Swagger module I'm not getting the hints for Swagger module and document let's import manually cannot find a module nestjs worker why I think I have to install it manually and install next just swager now the error is going now we have a Swagger dependency here we have the nest F package you can write the name of your title application and you have to write the description version and finally we got a call the build and we are creating the document and we have set up the Swagger module it's time to run the application oh there is an issue it was an extra parenthesis application is running now let's try to test it I can go to the Local Host colon 3000 SL API now we have the title of the document and the description we have all these routes but we did not add the tags I'll show you tags in the next video let's try to send the request to the root URL so I got this response hello I am learning nests fundamentals if I execute this endpoint I got the port the 200 status code in this lesson I'm going to teach you how to document this signup route if you look at this signup route I don't have any schema yet it's not displaying the schema what type of parameters do we need do we need first name do we need last name I also want to show the description or the purpose of this signup route first of all you have to add the API tag to the O controller let's convert all these routes into o section we're going to place the login route into OD section enable to fa and validate to fa let's do it first I'm going to open the O controller here I can say API tags I can use the Au my application is running now you can see all the routes are placed inside the O section one more thing I would like to add in the O controller we have to decorate the sign up route the next step we have to add the API operation and the response I'm going to use the API operation we need to get it from this Swagger module it will return the user in the response with 2011 status code this is called please register a new user make sure it's running now let's refresh I cannot see the sign up rout I think it is taking too much time oh I found the error API response we need to get the API response yes we have the API response let's restart the [Music] application now you can see that we have the register user we have specified it here somebody which is registered new user and you can see the response it should it will return a user in the response let's try to test it if I if I provide first name NH last [Music] name shsf and we have to provide email SN gmail.com let's provide the password 1 2 3 4 5 let's try to test it out internal server error because let me look at the error entity metadata note found no metadata for a user was found I found there is an issue with type orm and a web pack if you use vbac hot reloading like we have used weac package to reload the application fast type orm does not work with this configuration like this one we have to replace it and you have to register all the entities manually but it can work with migrations there is no problem with migrations but you have to replace it here we have to import couple of entities application is broke now I think I have to restart it application is running fine let's test it out I'm going to create a new user a user has created successfully you can see that with 2011 status code when you look at the sign up route if you check schema it is not displaying me in the schema what do I mean by schema here I cannot see the login dto I don't have create song dto I don't have create user dto it should display me the schema let me run the application my application is running now if you look at the schema in the signup route you will see the empty create user dto you can fix it with the help of API property you have to tell Swagger hey this is the API property I want to I want to see in this Swagger document let's add API property in the user entity we have to do it here please provide the first name of the user first name of the user let me import API property you have to do the same thing for last name you can also add example like what could be the data type look like I'm also going to add API property for email let's do it for the password my application is running now but I cannot see this schema value I cannot see properties here for my schema you have to register nestjs Swagger plugin you can do it in the nest CLI I'm going to copy the plugins open nli and I'm going to do it here let's restart the application because we have modified nli let's refresh the application I cannot see my schema I have to register the plug-in inside the compiler options that was the mistake restart the application now you can see the schema value first name last name email and the password it will also show you the schema value for login dto here we have the user example value email ID API key playlist in this lesson I'm going to teach you how to test Authentication in Swagger document we have to enable barer o it's a scheme you can do it in main.ts file you have to add this function Nest Swagger module provides this function add barrier o this is the type HTTP scheme is barrier format should be JWT name is JWT you can add you can add the description jwd token and I would like to provide in the header this is the name when you need to use or apply on the controller function one more thing we also need to update the secret key in the JWT strategy I don't want to use o constant. secret I I have to get it from the process.env secret this get profile is our protected route if you want to apply authentication or app if you want to protect or apply authentication of swagger document you have to use the API barrier a and this is the name we use jw/ here this one like create songs endpoint is also a protected route you can also apply authentication on that in the songs controller these are all the protected routes only artist can access update endpoint delete endpoint and create endpoint so you can apply Authentication on these routes as well but I just want to show you the demo in the app controller we have this protected route get profile endpoint let me show you in our Swagger document SL API here we have login route we don't have any authentication section let's implement it first of all let me write documentation for login route inside the O controller it looks good now we have to enable the authentication I'm going to copy the code and paste it here now we have to apply JWT authentication we also need to update the secret key in the JWT strategy I don't want to use o secret from the O constants let's get it from the environment variable and this is we have to use I'm telling to Swagger hey Swagger this is the protected route application is broken now restart the application I found an issue when you are working with we hod module reloading do not save the application if your application is in error format if there is an error in the file do not save the application otherwise it will break the V hod module reloading now it it will take some time to restart the app application application is running now I have to refresh my page now you can see the authorize if I try to access the profile route from here it should give me the error unauth red so you can you have to log in to get the access token I'm going to send the login request password does not match what was the password 1 2 3 4 5 6 I have got the access token now I can use this token and I'm going to provide it here this is the name JWT o you can see that authorize Now by enabling this JWT o here this Swagger will use this token just like we saved here let's access the protected route you can see that I got the user ID and the email it has already attached authorization barrier and the token if you have all protected routes in the controller you can also add API barrier or here for all controller routes but I have only single route is protected protected this is the public right route that is why I did not use the API or o barrier or inside root inside the controller for a controller so I applied separately API or API barrier OD you can also Define the tags for songs controller I want you to do it you can apply High authentication on songs controller protected route like create is a protected route you have to add API or o barrier decorator here it did not create the aay tax because my application has broken now by using this code restart the application my application is running now I can see all the songs related route you can also do it for the playlist API TX you can see the playlist section in this lesson I'm going to teach you how to install mango DB using docket compose if you don't have installed mongod DB on your machine you can install it manually or you can install with Docker compose I have already installed Docker on my machine my Docker is running you can see that here is my Docker is running now but we don't have any project right now to use with mongodb I don't want to install mongodb in my previous project we're going to create a new project to play around with mongod DP database I want you to create a new project I can say Nest new and we need to provide the name of your project I can say n production nestjs project with mongod DB and I want to ship it on production level you have to choose your package manager I'm going to use npm it will take some time to install the dependencies my project has created successfully all the dependencies have installed I'm going to go to my project I'm going to open the project into my vs code let me run the project by using npm Run start Dev let's commit in it and I would like to create a new Branch I'll store this code into this branch [Music] to connect with mongodb we will install this dependency or this package in the next video or you can install it here we need NCS mango package and we need mango separate package this is the magic we need to implement we're going to use docket compose to start mang DB driver I'm going to create a new file in the root directory I can say Docker compose EML you have to Define your version I can say one you have to define the services here we need to define the service mongod DB or mango mongodb the name of the service you have to provide the environment I can say mongod DP database and we need to provide the name of the database which is test we also need to provide the image we need to get the local uh latest image from the docker repository Docker Hub or you can say let's define the port I'm going to copy the same code I don't want to make mistake that's it or you can change your database I can say Spotify clone now you have to start MB driver you have to execute this command do compose up my project I'm going to open my project into R directory and let's execute this command I think already allocated I think my already project is running on 2701 docket compos let me stop that project project here we need to stop it let's try it [Music] again now it is going to start the mongod DB I'm also going to use external tool it's a graphical user interface mango DP Compass you can install it you can play around with GUI with mongodb database this is the GUI mongodb mongodb Compass you have to have a new [Music] connection you can have a new connection it is going to ask me the host and the port I can say Local Host and this is the port 2701 because my mango DB is running on this port 27017 so I'm going to connect it and you can create a new database Spotify clone and you can have the collection which is songs you can see that I have interacted with mongodb database and I created a new database so our mongod DP driver is running successfully in the next video I'll teach you how to connect nestjs application with mangos or mongod DP in the previous video we have installed these two packages mangos and nestjs mangos if you would like to connect nestjs application with mango or mango DB you have to create a new module in the app module you have to create it by calling the for root method this for root method is similar to mango. connect from the mango package you can read the connect package from the official documentation what I want you to make sure your mongodb is running my mango mongod DB driver mongod DB is running with the help of Docker I use Docker compose up here it is running Docker compose up now we have to call this method mongos module. forward in the app module make sure you have this database Spotify clone if I run the application let's see what will happen npm runs start def mango module because we did not import it let's import it with the help of VSS code I'm going to save the application you can see that Mango's package has installed it has also initialize the mango score module dependencies it means we have successfully connected to mongod DP if I will write the invalid Port let's see what will happen I'm getting the error mangos module unable to connect the database so it means we have configured the mango DB with nestjs but if you look at mango Compass I think I don't have Spotify clone database it can work without creating the database if I create the database it will work I can create the name of the collection now we have Spotify clone it looks good now we're going to create schema using mongos model in mongos everything starts with schema each schema maps to mongodb collection and different finds the shape of the document within the collection schemas are used to define the models and models are responsible for creating and reading documents from the mongodb database so we're going to create the first schema you have to create a new folder songs here you have to create the schemas folder and you have to have a schema which is songs. TS file but we will use this song document when we will inject the model into song service you can use the decorator schema nestjs mango module provides schema decorator this prop represents the property in the collection we will have songs collection and inside the song collection we will have these Fields Title release date duration and the lyrics Yep this schema decorator marks a class as a schema definition it Maps Our Song class to mongod DP collection of the same name but it will add S at the end of the final mango collection name will be songs and prop decorator defines a property in the document and finally we will have schema Factory it will return the raw definition of schema I logged on song schema and I got this result schema object we have these properties title release date and duration and couple of metadata for each field this is how you will create a schema I want you to implement it so I'm going to implement here by creating a new folder inside these songs we will have schemas here I'm going to create a song schema or song. TS file I just pasted my code we have defined four Fields I got all these properties from our previous project which we worked with tym and post I got title release date duration and lyrics I set this data type for dur string I couldn't find a Time Field Time data type in mangos so you can validate manually duration by using third party date plug-in so we created the schema successfully this lesson I'm going to teach you how to save record in mongodb database we're going to save record card in mongod DP collection right now we don't have a songs module we don't have songs controller we don't have song surveys we're going to create all these stuff and then we're going to create post end point inside the songs controller you have learned how to create the post endpoint how to create network request object or data transfer object dto and then I'm going to use song song service song service has create method to save the record in mongodb collection and finally we will create create song dto object inside the create song d. file and here I would like to inject the model remember schema will act as a model you can use schema to generate a model so I'm telling please give me the model the name of the model which is songs and I would like to use here I would like to inject it as a dependency I remember I have created the type in the song schema file I got the song document and this song model provides crud operation create read update and delete it is similar to type orm repository it will be treat treated as a type RM Repository and finally we have a safe method in the song model and I am going to call the method here it is going to return the promise and finally we have created the songs module we have to inject the song model just like we did with type orm repository if you will not do that part you will not be able to inject song module here that's why you have to register it as a here I'm telling to njs I would like to use song model in the service or in my provider and then you can send the request to this URL to to create a new song in the mongod TB collection I want you to implement it let me implement it for you let's generate let's generate controller songs let generate so service songs it has created the songs module it has also updated the entry in the app module you can also see the songs controller it has also updated Creed the songs controller inside the app module you can see that now we have songs module inside the songs module we have songs controller and the song service now it's time to create a new endpoint I'm going to copy the code inside the songs controller we just injected the song service right now this create method does not exist in the song service we also don't have create song dto Let's create let's create create song dto I'm going to create a new folder dtos and I'm going to create a new file file create song hd.s file that's it I already taught you how to create a method in the service let's refactor the song service add a new method we have injected the song model make sure you provide the name of the song model here we are injecting the song model and I called called create method from song model and finally we have to tell njs I want to use this song model in the songs module so please make it injectable and now we have to run the application I have to import song dependency song it looks good we have to test it I'm going to create a new file to make API request I can say api. HTTP let's send the API request you can see that a song has created we can verify from Compass here is the record inside the songs collection let's add another song so we have another song it should display the second song but I cannot find out no I can see the second song we have two records in mongodb collection this is the document if I don't set the title what will happen you will see internal server error because we have set the validations inside the song schema these properties are required title is required release date is required and duration is required in this lesson you're going to learn how to implement find and delete method we will create two endpoints to handle find and delete request let's start implement it I have already taught you how to implement crud or rest based API end points let's create a method find to fetch all the records from mango DP collection it is going to give me all the documents now we have to create a route to handle the request our application is running now let's send the API request to fetch all the songs we have to send the get API request we don't have any record yet let's create a new song I have I've created a new song I'm going to create another song now we have two songs let's fetch all these songs we have successfully implemented the find all method now it's time to implement the find by ID I'm going to create a new method find by ID in the song service and there is a method find by ID in the song model you have to provide the ID we're going to get the ID from the request parameter let's create a new route now we are going to send the request to fetch song Only based on ID find one song we have to get the ID I'm going to send the request to fetch all the songs now I'm going to copy the ID and we need to provide the ID here so I got the single record on the based on ID you can also implement the delete endpoint I'm going to create a delete function inside the song service song model provides delete one method and you have to provide the ID mango work works with underscore ID if you have worked with mongodb the ID stored ID stores in this underscore ID format if you if you are using or have used postgress or MySQL in my SQL or postgress you say the primary key or primary ID with this ID without underscore now we have to create a delete endpoint in the songs controller we have to get the delete method that is it let's create a new song because we're going to delete that song I'm going to get the ID and now we have to delete the song to send the delete API request delete song you can see deleted count is one acknowledged true it means we have successfully deleted the song you can double check it by sending the API request to fetch all the songs and you can see new song does not exist here you can also implement the update functionality I already taught you when you were learning type or mcard operations similarly you can implement the update operation you can have you first of all you have you have to Define update function Here song model provide the update method you can use that method and then you got to create a controller to handle the update request in this lesson I'm going to teach you the concept of populate if you want to make a relation or a reference between two document between two collections remember in mongodb collection collection will have documents in my SQL or post you will have tables and columns so if you want to make the reference or relation between two collection you can do with the help of poate you have to implement the concept of poate I have this use case or scenario each song must have must belong to one album and each each album can have many songs I want you to implement it if you want to do that you can Google Mongo's relation or check the official [Music] documentation this is our album schema we did not create the album schema yet I'm going to teach you how to do that or you going to create or you can create the album schema just like we did the song schema scha it is going to take the array of the songs because each album can have many songs that's why I created the array of songs and you can have multiple types it's an array I got the types from mango package here you will see type from the mangos and I'm telling that the reference is songs because when you create the song when you created the song schema you have defined a class for class song by default the collection will be songs you can also double check it from mongod DB Compass let me show you I'm telling you I would like to make a reference with songs [Music] collection let me do that inside the Spotify clone we have the collection name which is songs I have added the reference here and finally you also have to add a relation for this for the album in the song schema I'm creating a property and type should be Mango's object ID or mongodb object ID here I'm I'm getting the or defining the reference album. name it should be albums and we have the album and finally you got to create album module just like we did the song module and I'm saying I want to use the album model in the album service or we we will be able to inject the album model to perform crud operations and here I have injected the album model in the album service just like we did songs model inside the song service and I created a new method we will have a create album dto and here we will have find albums this is how you will implement the populate let's say you want to display all the songs on the front end against each album then you need this query you got to I'm telling to mongod DB please give me all the albums please give me all the albums for each Album please also give me all the songs this is how you going to do it and create when you are trying to create a new album you got to provide the title and the songs it should be the IDS and we have create method to create a new album and uh find all albums and you also have to refactor create Song D you can implement it I want you to do it I already taught you all of these steps to do that first of all we have to create album nextest generate nextest generate module albums or I can say albums and next gener at controller album and Nest generate service albums Nest generate module albums Nest generate controller albums Nest generate service albums I don't need spec files I'm going to delete them now you have albums module albums controller and album service it has also added the entry in the app module let's create a new folder schemas I have to create create a new schema I can name it to album schema. we will also need a dtos now we're going to I'm going to copy album schema and I'm going to paste it here that's it and I can use I also have to refactor the song schema we have to add another property one thing I forgot to add it should be a mongodb property that's I forgot to add add prop decorator for the lyrics property we need to get the types from object ID from mango we also have to import the album from album schema everything is good right now let's create we have to update album module actually we need we need this line I'm going to copy [Music] everything e we don't have dto let's create that create Alum dto now we have to define a controller we already created the controller I can say should be albums controller album service and we also need to refactor the create song dto I have found the error in the album service get rid of the song Let's import it here if I save the [Music] application we also have to refactor in the song schema everything is good now what we what I want to do I would like to create the album first create album we have to send the post request by providing the data it is going to get give it is going to asking me the name of the album title title of the album let's say dance and I would like to provide the array of the songs I want to save let's say these two collections these two collections inside the dance inside the dance [Music] album I'm also going to save this document or save the song inside this album let's create a new album I got the eror song validation failed duration duration is required OMG I forgot to add the albums here now you can see that I got the dance album with these two songs now we have to fetch all the songs I'm going to test the popular method popular functionality find all [Music] albums with songs this time we have to send the get request let's fetch all the albums you can see that I got the albums array this is the first album and we have all the songs against each album this is how you can make a relation or reference with document with collections or with models in this lesson we're going to prepare our application for deployment I'm going to teach you how to deploy nestjs application at Railway you will also deploy your postgress database at Railway we're going to deploy our application this one the Spotify clone which we were building our application is using postp database with type orm I'm going to teach you how to deploy the complete application at sailway first of all you got to create a new project make sure you deploy your project at GitHub repository I did not deploy the project yet first of all we have to do a do a little bit configuration we have to set our environment variable when I will run the application in production it should run this production. EnV file if I'll be working at development environment I want to work with local post database I don't want to change in production level so we got to configure a couple of settings we already created the env. development. env. production but it is not configur configurable when my project is running in production mode it should pick this production file I've already written down the validation in EnV validation for node environment but I did not set in the configuration let me do it I can say node EnV and I can get the value from process dot process. env. node EnV now this variable is available for the config service I've already provided you the nests deployment raway started kit BR started kit project you have to open it and run npm install to install all the dependencies now we have to configure the EnV file path in app module get rid of this stuff I don't want to do it configure get it off this middleware get rid of this data source here we have to update our path what I can say please get the value from process do do EnV do node EnV or you can say get the path from the current working directory and you can provide the name of your file current working directory and Slash dot here we need to do EnV dot development or production we have to remove this one please get the working directory and find the env. production file or env. development file we have to set the script or we have to set the development environment in our package.json file for the dev I can say I want to mention node EnV to development we have to do it here we have to set the production value when you run the application with production how can I test it in the main.ts file maybe I can use that or what can I do yeah I have the access to config service I can say console DOT log config service doget I can provide the name which is not EnV let me part it to string let's see what will happen you can see that it's working fine now my application is running in the development environment if I run the application in produ prodction environment when you see the production. environment I don't set the I didn't set the database configuration so it will not work my application will be crashed let me show you you can see that my application has crashed an instance of environment variable has failed yeah it is showing me the validation error dbport does not exist DB host does not exist if I copy this configuration what will happen now it should run the application you can see that my application is working fine now but we will replace these configurations with Railway post configuration I have everything in the master Branch let's create the GitHub repository because Railway will be asking for GitHub repository let's create a new repository I can give any name nextjs deploy to railway if you want you can create private repository I'm going to make it public we have to add origin it is asking me to create push as a main branch let's do that so I got the main branch everything inside the main branch let's try to check it out so I have everything in the main branch now we have we have EnV doev development we have env. production you should not push your env. development or env. production to the GitHub repository because we wanted to set it to the kit ignore do not add Dov files if I add. EnV update get ignore we have to push the code I try to add do EnV in the G ignore edit I try to add EnV in the ignore and it was not not working I also removed the cache for env. development and env. production file removed envs now we have to push it oops envs let's push the code let me delete this file manually I'm also going to delete env. [Music] production now we got to pull the code everything is up to date right now if I try to push you should not see env. production and EnV do development file so we have pushed the source code to our GitHub repository you going to say deply from the GitHub repository here we have to configure our repository I can say deploy njs app to I can say now it is going to deploy the code it is building and running env. production no it is trying to building the project now you can see that our project has deployed if you want you can see the log what is going on here I got this error instance of environment variables has failed in the valid validation that's an issue we have to configure our environment variables our application has crashed now we have to set the environment variables first of all I have to create a new database it's very easy to create a database in real way just right click and find the database I'm going to have post now you can have the post when you see the connect here you can find your database option I can say this is post and you can up create your EnV production file EnV [Music] production oops I deleted that files we need to get back our development. EnV file do env. development and I also need to get production EnV file now I'm going to copy my database in the production let's do it here [Music] database this [Music] one and we need PG Host this one and we need password I want you to use your own password do not copy my password username it should be post it's working fine you also need a port everything is good to go now now I want you to copy these EnV file the your production EnV file and open the N nestjs deploy to raway project and in the in in the variables you have to set your environment variables that's it I'm going to update my variables now it is going to redeploy the app application now redeployment is in progress It's Time to it's it will take some time my application has deplo deployed now it is going to start let's look at the deployment logs amazing I I was logging the production in the app module or I think I was doing in the main.ts file you should not do that it's working fine it means we successfully deployed our application so how can you test it maybe you had thinking about it how can I test this application right now we don't have any domain let's generate domain to test the application uh if you want to refactor you can change that I can say Spotify clone production now we have this domain name I'm going to open it it is going to give me the nothing here don't worry when you try to access the API routes it will take some time because we have set the domain name it is going to take some time now it's working I think fine now after 30 seconds my project has Reloaded now we're going to figure it out I'm going to send the API request to test the application it is working fine now but what will happen if I try to create a new user let's say I want to perform database operation I'm sure it is going to give me the error let's create a new user Jane Don Jan gmail.com 1 2 3 4 56 I'm going to send the request I got internal server error you can check the log what what is going on users does not exist because my database is empty now we did not implement the migration remember you have seen in the data source we have set this synchronized to false but do not use synchronize to true in production what we have to do we have to run our migrations to perform changes we have to add relations because I done that I've done it I think I don't want phone migration you can delete that now I have to execute these queries these queries will create table in our postrest database here here what we have to do we got to run the migrations I got this issue we have to migrate the database in the production so we have to use a migration make sure you are using the password process. env. password not a DB password because we have defined the password in our environment file we have to run the migration I'm going to run the script npm run migration I would like to create all my tables that's why I just provided the name in it so I got the undefined process. I'm doing the log for node environment I'm also doing the log for DB DB host I'm also doing the log for DB password you can see that I got the development value it is working fine but when you look at the env. development I'm using the database for the Local Host like post gra local instance here I'm using the railway postra instance so I have to tell to nestjs build command under the they are using generate command is using njs build command this one type orm but I want to say please run the produ run the project in the production let if you want to run the de in migration in production you have to Pro tell njs project you can create a separate script for build for production or separate SCP for separate script for build in the development environment but you can do quickly by using say that export node EnV here I want to set the node environment variable to production now you can see development environment should be in the production I'm going to run the migration I've also logged the node environment it should give me the production by default it if it if it logs production it means it is going to run the production EnV this one you can see node environment is production but I got DB host is empty undefined and password I figured it out the issue I have to install do EnV package and here we have to use the EnV package it is not getting variables from EnV because we were using the config module for config configuration after installing config module do EnV package you have to import it here do en/ config now you should be able to access these variables so I'm going to run the migration before running the build you have to set the node envirment do you want to run it for production or do you want to run it for development but if you want you can create a separate script SE separate build script for production and development I still got the eror production it's not getting the value I think it is not finding the env. development file so there was an issue it is not loading the EnV from the env. development. env. production if we will have simple. EnV then EnV package can get variables from the file but right now it is not getting it so you have to provide the custom path I just did a little bit configuration we have to import the path we have import the part so we have to use this syntax require this one all I have to do is provide the EnV path now it should work it should get the values so I'm going to create the migration cannot read property PA is equals to path but I got still undefined let's log EnV path oh it is getting the value from DB but my file is located at root folder so it is not here inside the DB if I try this one I tried to work with this env. production with custom path but it is not working all I did if I change EnV it is it will work let's let me show you get rid of [Music] everything now if I copy that and create EnV file in the root directory it will work I found there is an issue with type orm now I'm going to paste my code for production you you have to adjust nestjs build when you try to run the migration you have to update the changes here I found this is the way you can implement it but there was an issue with custom file path so now it will work I'm going to run the migration now I can see production and the my container name which is my DB host and my password now migrations has been generated successfully it's time to run the migration we got to run this command npm run migration run should be run you can see that it is running all the queries creating tables in the railway postris database now you can understand you can use this EnV for type orm build use it for type or RM migrations because in the app module we are using the configuration of config module we are not loading this EnV file we are loading envir environment development env. production file but you can use this EnV for migrations now we need to double check it we have to deply our code now it will take some time to redeploy the application the application is running now I got this secret key the database host and the password now we're going to run it/ API open this Swagger tool you can also double check it from postris database I have only migration table it should give me all the tables but something went wrong here inside the migration the record is empty table is empty unique key primary key what is going on oh I have two migr ations get rid of this file get rid of all these migrations let's generate the migrations from the scratch I'm going to name it to in it now migration has R it successfully I'm going to comment this code now you have to run the migration everything is good to go all the ques has have executed now you should see the data in the data datase you can see I got artist playlist songs and users table we have these columns if you want you can run the seed from App module I think we we were doing seeding in main.ts file you can enable this code application is running now let's create a new user amazing we have created the record successfully you can also double check it from the post database you will have the user here but I created this user from the this one from seeding because I think my seeds are running constantly I think I enable that seed in the app module we got to disable it otherwise it will generate more users I'm going to remove them now you have to see constantly a new data I can say disabled seats now it is going to redeploy the application so this is how you can deploy nestjs application to railway in this module I'm going to teach you how to do unit testing integration testing and end to end testing for nestjs application before getting started on testing I want to teach you some of the basics of just because we're going to write a lot of mock functions we're going to write we're going to write a lot of spying spy functions you will learn how to create Mo implementation of service of a controller of a repository if you know the basics of justest if you know mo functions if you know spy function then you can skip these three lessons if you want to refresh the knowledge of just you can continue this video just as you if you don't know about just just is a popular JavaScript framework it is developed by Facebook you can use for testing JavaScript application you can use just with react view angular and nodejs these are all the function alties of the Gest asynchronous testing code coverage snapshot testing moing and spying we're going to use a lot of moking and spine with nestjs that's why I want to teach you these two concepts in more details you will learn how to do matches and test suits and test running and assertion uh before creating the just project I want you to open an empty folder we're going to start it from the scratch and you got to create package.json file I can say npm in it d-s please create the package.json file for me I got the package.json file now I'm going to copy that and let me replace that here what I want to say we we need to install the typing of the justest we need to install the justest app a Dev dependency and I created the script to test the justest if you want to run the justest in watch mode I'll teach you how to do that you got to run you got to run this script so uh please install these two dependencies I'm going to install them it's going to install the dependencies let's create a new file I I'm going to name it to some .js file we're going to test this function we're going to write test cases to test this function in the third step we have to create some. test.js file I'm not using typescript here I just want to show you the basics that's why I want to keep it more simple we have to import the sum function from the sum. JS file I have to write the test case at 1 + 2 = 3 now we're going to write the test case you can use the test it should give me the result 1 + 2 = 3 so we're going to call this function it's going to take the call back function I can say expect it's not giving me suggestion because it is taking too much time to install the dependencies because I think my internet connection is slow right now so we need a [Music] function sum. 2 B 3 we have to call that function it is going to take two arguments if you look at the sum. JS file you will see two arguments A and B the first argument I'm going to provide one and the second argument I'm going to provide two let's try to test it out it's still working npmi minus TJ my both packages have installed just in the typing of the just now you can write the test case I've written the test case you can run it npm run test I would like to run it in the watch mode dash dash watch is not sported so you have to write the watch all now you can see that I have to update the script for the watch all now we have to select the pattern I would like to run this s test.ts file right now we have only single file it's going to execute this file the test has passed now if I write the invalid value I save the changes it has started automatically and I got the error expected four but received three you can play you can play around with multiple matches function let's say 1 + 4 or to have been called to have property to have returned to have returned with let's say five you can play around with multiple watches received have as type number so this is not a right matcher function so I can say it should be five this is how you will write your first test case now I'm going to teach you the concept of mocking we're going to play around with mock functions Auto mocking inest refers to the automatic creation of mock implementation for imported modules or dependencies during testing let's create the mock functions you can use the mock function to track the function calls if you want to remove the dependencies we're going to do in njs testing we're going to remove maybe the implementation of service implementation of the service then we will have more implementation we can simplify the testing and control behavior when you do the unit test your code let's say if your code is dependent on five dependencies let's say if your class is dependent on on Class B Class B Class C or class D let's say and you want to do the unit testing let's say this is the class A now Class A is dependent on let's suppose Class B Class C and class D now Class A let's suppose we has two function or one function if you if I want to test the one function from the class A when you do the unit testing you test the individual Parts you test the individual functions to test the individual function maybe the individual function of Class A is dependent on the function of Class B function of Class C and the function of Class D then we have to write the mock implementation for the class B Class C and the class D I'll teach you in the later videos now we're going to create mock function this is how you will describe or you can group all your test cases into a group describe I want to write all the mo function examples in this section it is similar to the test you can Define the it or the test it is referring as a test so it should create the basic mock function let's create a new file Mo function. spc. TS file I have created the test.js file but you can also create the spec. JS file the concept is same now now we have to write the mo function here I can say I will provide the mo write Mo function examples here this this this section will have the mo function examples let's write our first test case it should create a basic Mo function should create a basic mock function you can create a mock function by using the just. function I can say this is the mock function just provide is a FN now we have the empty Mo function if you log the mo function you will see this is the empty function let's try to do it run the script again to run the Tex test in the watch mode this time I'm going to add the pattern for the more Dash function. spc. file it is going to ask me the pattern I can say mock now it's going to run this file if you see the log you have a function a mo function if I call that you will see there is nothing here we have undefined function if you pass the argument it is going to still it is going to still give me the undefined this is the empty mooch function if you want to return the value from the mock function you can also do that return value Mo return value now let's say I I would like to return the four now if I call that function it should give me the value of four I can write the match functions on it mock I call the function to be the value should be four you can see our test has passed now if I add the invalid value which is three it's going to give me the error expected three but received four if you want to remember I told you you can also keep track the calls of the function with the help of Mo how many times this function has cost called mo. calls. length to be we have called only one time so it should give me the length is one if I call the function two [Music] times Mo function dot to have been called been [Music] called let's say I want to call that function and I'm expecting the four it should give me the error you can see that the save to expected is one here we have the error it should give me the two because we have called this function two times if you want to keep track of the calls of the function how many function have how many times you have called the function you can also do measure on that here I can say expect mock function to have been called it is checking that did you call the function yes we already called two times this is how you you can return the value from the mock function you can create you have learned how to create the basic mock function now you're going to learn how to create a basic Mo function with arguments we did not create a function with argument we just created a basic mock function then we have returned the value here I can say it should create a mock function with an argument let's create a function con mock song function you can say song mock just. function it can have create song dto let's say that mock create song and this function will have this argument but I also want to write the implementation you can do that as well well right now we did not return the value if you want to return the value you can do this stuff it is going to return a song title animals and ID or you can oh animals and ID which is one let's say that that if I am expecting on that it should give me the same object animals ID which is two or ID which is one if you want to test the object you can use this two equal expression make sure you have called that function with argument create D is not defined title should be animals create D is not defined I think it will not not work we have to write the implementation here I just want to show you the another alternative path it's a call back function it's g
Original Description
Learn NestJS in this comprehensive course for beginners. NestJS is a framework for building efficient, scalable Node.js web applications.
Code: https://github.com/HaiderMalik12/nestjs-fundamentals
Course resources e-book: https://www.haidermalik.dev/nestjs
Testing Starter Kit for Module 12: https://drive.google.com/file/d/1dU4ro10jZaIYAu32MwQFr4UHlY6GFu6O/view?usp=sharing
✏️ This course was developed by @haidermalik3402 . Check out more of his courses: https://www.udemy.com/user/5512f7602d2ad/
❤️ Try interactive JavaScript courses we love, right in your browser: https://scrimba.com/freeCodeCamp-JavaScript (Made possible by a grant from our friends at Scrimba)
⭐️ Contents ⭐️
Module 0
⌨️ 00:00:00 What is NestJS
⌨️ 00:03:01 Create NestJS Project
⌨️ 00:05:30 NestJS Directory Structure
Module 1
⌨️ 00:07:00 Creating Controller
⌨️ 00:11:07 Creating a Service
⌨️ 00:18:09 Creating Module
Module 2
⌨️ 00:24:27 Middleware
⌨️ 00:32:39 Exception Filter
⌨️ 00:43:07 Transform param using ParseIntPipe
⌨️ 00:48:10 Validate Request Body using class validator
Module 3
⌨️ 00:52:09 Custom Providers
⌨️ 01:15:26 Injection Scopes
⌨️ 01:20:59 One To Many Relation
Module 4
⌨️ 01:35:05 Establish Database Connection
⌨️ 01:43:42 Create an Entity
⌨️ 01:50:43 Create and Fetch records from Database
⌨️ 02:08:54 Pagination
Module 5
⌨️ 02:17:44 One to One
⌨️ 02:24:14 Many to Many relation
Module 6
⌨️ 02:43:51 User Signup
⌨️ 03:00:05 User Login
⌨️ 03:08:12 Authenticate User with Passport JWT
⌨️ 03:24:42 Role Based Authentication
⌨️ 03:46:51 Two Factor Authentication
⌨️ 04:17:41 API Key Authentication
Module 7
⌨️ 04:32:52 Debug NestJS Application
⌨️ 04:37:00 Migrations
⌨️ 04:49:51 Seeding
Module 8
⌨️ 05:02:02 Custom Configuration
⌨️ 05:24:29 Validate Env Variables
⌨️ 05:35:48 Hot Module Reloading
Module 9
⌨️ 05:45:51 Swagger Setup
⌨️ 05:52:30 Document Signup Route
⌨️ 05:58:28 Create Schema using ApiProperty
⌨️ 06:02:54 Test JWT Authentication
Module 10
⌨️ 06:11:40 Install MongoDB using Docker Co
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from freeCodeCamp.org · freeCodeCamp.org · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
Dates - Beau teaches JavaScript
freeCodeCamp.org
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
The Definition of Ready - Agile Software Development
freeCodeCamp.org
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
Working Agreement - Agile Software Development
freeCodeCamp.org
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
Definition of Done - Agile Software Development
freeCodeCamp.org
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
The INVEST approach to product backlog items
freeCodeCamp.org
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org
More on: LLM Foundations
View skill →Related Reads
📰
📰
📰
📰
10 Most Common Mistakes Java Developers Make in Interviews
Medium · Programming
# C++ Error Messages Translated — 10 Common Compilation & Link Errors Explained
Dev.to · Yilong Wu
# Picking What to Read Next: The Trade-offs of Ranked-Choice Voting in a Django App
Medium · Python
The Ultimate Rust ORM Comparison 2026: Diesel vs SQLx vs SeaORM vs Rusqlite — Pick Your Powerhouse!
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI