Nestjs CRUD example with MySQL & TypeORM

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys in this video we are going to learn how to perform crowd operations in next.js we are going to make use of type orm and mySQL database just to point out the approach we are going to take here we apply to whichever SQL database you use for example postgres sqlite Etc so what we're going to do is to create a next application and then we configure database connection using typo RM then we create entities which are going to be mapped to the tables in our database and after that we go ahead to see how to create read update and delete all right let's get into it before we proceed you need to already have my SQL installed in your machine installing and setting up MySQL is outside the scope of our next tutorials so you need to get that installed and ready to connect the another thing you can do is to install the nest.js CLI which we can use to generate a new project and do other stuff so you can check the next documentation it is actually straightforward to install the CLI and ready to use to generate a new project we use the command Nest new and then the project name so I'll head over to the terminal where I want to create the project and I'll say next new let's call this a cloud app and hit enter then we are presented with option whether to use npm or yarn I'll go ahead with npm then we wait for the installation to complete the installation has completed our CD into the project see the cloud app then open that in the code editor I'm using vs code before we go further let's just run our application to be sure that everything is installed properly so we can say npm run start Dev this will start the application in watch mode to watch for changes and update the app has started we can check it out by visiting localhost 3000 on the browser to see the output so our installation is okay stop the server and go ahead with some configuration the first thing we need we want to do is to install type urm and those dependencies we need for database connection this is going to install type urm and MySQL so I'll copy this command and head over to the project and run it then we wait for the dependencies to get installed now we have type urm and MySQL added let's see how to connect to the database using those so over here is an example connection we are going to make use of this for now but we are going to change some things later so I'll copy this this is what we need I'll copy from type 1 module dot for root head over to the project let me close this one head over to the project SRC folder and then app.modu.ts in the Imports array is where we want to go to the one once there here we want to paste the configuration that we got from the documentation and make sure to import the type URL module so let's look at what we have for this configuration the first item here is where we specify the database we want to connect to in this example MySQL you can see there are other options melodyb mongodb postgres Etc but for our use case we are making use of MySQL and then you have your specific database connection credentials the host is localhost I'm okay with that port.306 and then username root that's the username of my database password I'm not using any password for my database connection and database I have a database named demo which I want to use for for this we are going to come back to password letter because we don't want our password committed to in the code right we want to manage that let's say in the dot EMV file as an environment variable then entities is where we are going to specify the the classes that should be used to create or map to the tables in our database for example let's say we have user entity and we have payment entity this is where we specify those entities that should be used to map to the tables in our database we can also tell type urm the pattern it can use to Auto detect The Entity files in our code base and then synchronize this is when we want to automatically synchronize the entities with the database what that means is when we Define an entity for example user that has the field ID name password Etc if we set synchronize to true then type orm will automatically generate the corresponding tables in our database with all those fields as the columns and when we make changes in the entity file those changes are also synchronized or reflected in the respective database table one thing you should take note of is that this synchronize that is set to True is generally not used in production or in real projects while for a demonstration like this it can be very helpful it is better to take migration approach when working on a real project but migration is outside the scope of this lesson so we're not going to talk about migrations and all that at this point I want to save the file and run the application again to make sure that this connection is okay if if it is not okay I'm going to get an error when I try to run the application so let me run the app one more time and okay the application started let me try to use credentials that are not correct example put password Here save and run this again so I am not able to connect to the database because the credentials are not correct I will revert this so our connection is working as expected now let's go back to what I talked about earlier about having the password in the environment variables although my connection does not use any password but in case your own uses it what we're going to do is to create a DOT EMV file in the root so I will create a DOT Envy file then here I want to have DB underscore pass word to be equal to empty here you specify your own password I'll leave it empty but before this can actually work let's do it the next JS way so to make use of environment variables the next JS way what we can do is to install the config module that we can use to read from environment variables I will copy this let me stop this server paste it over here and we install the config module the installation has completed how do we make use of it we go to the Imports array of the roots module and list the config module there so what I will do is to go to SRC app module then over here I can put it at the top anyway it doesn't matter but let me leave it at the top and make sure to import the config module this is imported by default it is going to look for a file dot EMV as we have it if you want to customize your own differently you can take a look at the documentation to see how to do that with the config module setup we can now modify this database connection to read from the EMV file for that I'm going to use this um forward async approach that allows us to inject the config service this config service comes from the config module that we just ins we just installed I'll copy this head over to the code and replace the type orm options here so we make sure to import config service which comes from the config module here we have something similar to what we had before now we are connecting to mySQL but we are now making use of the config service to get things from the from the EMV file I have for password I have DB password so I'm going to change it to DB password we are going to add additional ones let's call this DB underscore name and in dot EMV let's have that as well DB name my database name is demo and DB username my username is root come on what just happened roots and let's call this DB ports what should we touch three zero six and finally DB host which should be localhost localhost we save that I think I have a typo here it should be comma okay we save the changes and try to connect with database again I will run npm Run start div and once again we have our database connection that means that our application is now reading from the dot EMV tool prove that let me use a database name that does not exist I will start I will stop and start the application again we try to connect and we get a failure let me stop this and revert the changes so now we are reading the database credentials from the config file the next thing I want to do is to generate a resource this will just give us boil some boilerplate for our Cloud implementation to do that I will use the next CLI next generate resource code to do's we wait for that um nothing happened so I don't know why I'm not able to generate resource with the command I've tried to update my next CLI in case that is the issue but it's not working what I will do is to wire things up manually instead so here I'm going to create a folder for to-do's then the first thing I want to do is to create the module let's call that to those Dot module.ts so here I'll export class Sports class 2. to do let me minimize this to do module for this to qualify as a module we use The Decorator module imported for the next JS common then the next thing I want to do is to create the entity file I'll create a file code to those dot entity entity dot TS let me name this to do here I will export class to do and for this to qualify as an entity class we use The annotation at n PT like that you can give the table a name if you don't want the auto generated name so let's call this to do's that should be our table name foreign in the module okay before we do that we need to wire up this module in the base module that is in the app module so here in the app module we come over here and just list it out to do module uh do I have a mistake somewhere no okay that is automatically imported up here our to-do module what we have here is an entity that has no fields that will be mapped to the introduced table let's go ahead and specify some Fields the first one I want to have is ID field that should be mapped to the ID column in the database then I want to have title this should be a string you can have other things you you want to have here but this should be enough for our demonstration I want this ID field to be primary key Auto generator so for that we use the primary yeah this should be it imported from the type orm module here I just have column so this is also a column but a special column the primary key Auto generated column this is another column we are going to have in the in the table that is introduced table you can override the name you can set other options so to do that to learn more about all these options you can take a look at the type urm official documentation there are more things you can do here but let's keep it simple so we can move fast to to performing some actions the next thing we are going to do is to import type orm module in the to this module and list the entities for that module what that means is in today's module we have only one entity now is to do entity so we head over to to this module here we say import so in the Imports array you want to have type type orn module dot for Fisher then an array let me format this inside this array we list out the entities we are interested in in this module so here we say to do that is the entity we just created there are different different ways to configure uh work with type urm we're using the one called the repository pattern where each of our entity has its own repository all right before we complete the setup for type RM there's one more thing we need to do if you remember when we talked about these entities we say that this is where we can list the entities for our application right for example we have to do now we can just come here and set to do but I'm going to change this because if you have 100 entities you don't want to maybe it's not so convenient to come here and make sure that all the entities are listed out but for now I'm going to leave it like this and try to start the application again I will come on start and we wait for the application to start over to the database I'm going to refresh so you can see that our table has been created with the fields specified in our entity class this is the ID field that is the primary Auto generated field and then we have the title column when we build an app our project or when we run the npm Run start div as we've been doing this is going to build the app into this folder as we can see here right so what I want to do is to tell type urm to automatically recognize all the dot entity.js file as our entity class so instead of listing out all the entity files here we can do something like this I'm going to paste the example make sure to import part from part so what this is doing is saying go into the dist folder and all the entity.js file or the dot entity.js file should be treated as entity file so this is going to work similar to what we had when we had to list out the entity files to demonstrate this let me actually let me first of all delete what I have here in the database refresh that is gone dismissed now I will start the server again and we watch type RM um I think there is a mistake somewhere I imported part I'm gonna figure that out later okay let me import join like this refresh now the application is up and running again if I refresh here you can see that we have the the table created again so we have successfully connected to the database and we are able to generate table thanks to this dangerous synchronize that we set to True here the next thing now is to start doing our crowd operations now let's create our to-do's service I will go to to those folder and create a file called to those dot service dot CS injectable export class to do's service let's have a Constructor where we can inject the type URL Repository so inside the Constructor we say at inject Repository then for which entity our to-do entity to do let's call this to do's repository or 2D Repository of generic type Repository to do so with this we have access to type orm repository for our to-do entity let's have a method for creating a to-do we can call that create and inside here I want to say const to do to be equal to this dot two to do Repository I'm using something I said okay these dots to do repository Dot create a to-do requires title the ID is auto generated but instead of hard coding stuff here let's have dto which is going to be of type title string this is something you can do with something like um class validator and then have that passed over from the controller I know that okay so we're expecting a type that has title within it so here I can replace this with dto at this point we're not done so the next thing we need to do is const let's call it result or just return await this dots repository dot save I want to do to save the results in a database because this is asynchronous we need to declare this function as async we save that then let's have a controller for our to-do's to those dots controller.ts here we say export class to those controller then once again we have Constructor and we inject our to those service private service come on choose service here let's have a method create so let's um you basically use the to do service that we injected in the Constructor so you can just say return these dots to do service dot create now this is expecting title which is a string let's say group food ideally this should come from the request so the user input instead of hard coding it here for that we can just make use of the request body actually the syntax is at body and we pass that over to the method create so as is it it stands our dto is of type any but this needs a certain type so what we can do is to refactor our code a little bit I'm going to end up creating a folder for details then I'll head over here let me no need for copying that I'm going to have in the details folder create hyphen to do Dot dto.ts export class create to do this is going to have title of type string so what I can do is to go over to the service method and I paint this like so create to do I will do something similar for the controller here I'll say create to do and the warning goes away for this class to qualify as a controller we need to decorate it with that controller to control yeah that's correct and for the route Handler for our method this has to be a post request so we say at post then our route prefix for everything to do is let's have to do's these are just next chance stuff I will save that what I'll try to do is to start the application again and try to create it to do by hitting that end point so let me change something here not spring okay whatever the name I'm going to change this to localhost 3000 which is where our application is running just on Postman stuff and I'm going to hit the end point slash to Do's localhost 3000 slash to Do's with the required payload and let's see what happens hit the end point we get a 404 this is to those so I think the reason for the 404 is that we have not wired up our controllers in the in the to-do's module to do that we say controllers and we list out our controller so to do controller and we also need the providers that is the injectables in this case we have to those service now we save that and try again to hit the end point we still get a 404 why do I still have a 404 to those localhost oh I have a typo here this is to do's save that and try one more time so you can see that we get a response with the ID that means that our to-do's has been created and inserted in the database to verify that let me quickly open it up so this is our demo database if I go to to those you can see we have a record there so we have successfully created our to-do let's move over to the next thing that is to update it to do unless fetch the record first instead of calling this read let's just call it find or or find me this is basically going to return all the to-do's we have in our database so for this I'm going to say there are different ways to query the database let me use this syntax return this Dot to this repository dots find inside the file we can specify options to filter things down for example we can say where ID is equal to one but this is type urm stuff you can check type URL documentations for how to do all these queries okay so I have a method to find many I will head over to the controller let's have that that should be to this controller let me copy this quickly paste it down here this is going to be a get request to slash to Do's endpoint let's call it find many we are not expecting any input here so find many I will save that the server is up and running head over to postman and hit that endpoint to find me so we get our list of available to-do's let's create another one let's call it um sleep send the request go to find again and we okay I think we filtered by ID over here so let me remove this we can get all the records send the request again and we have the two records alright guys so let's look at the next item please guys hit the like button and subscribe to the channel if you have not done so thank you as you do that the next thing we have to do is to update update so let's just reuse this because they are similar the payload for create and the one for update similar so I'm going to use the clear Syntax for this which involves first of all getting the record from database and then update so let's say const to do to be equal to await this dots repository dots find by ID find one that should be find one yeah find one this should take the ID of the item we are looking for so let's have ID here that is a number and we specify the ID actually the syntax takes a weird clause where ID is equal to the ID supplied once again this is I think so we say async you can do your check to be sure record exists but let's keep validations and other stuff in this tutorial so here I'm going to say um object.assign you can set this manually any I want to do it to do and our dto object Dot assign the copy over those records and finally we can say this or return yeah this dot repository dot save what to do await this finally we return to do head over to postman and give this a try cutting this returns to do so this is going to return the entity I'll put the return statement here let's head over to postman and we go to the update let's have title and then the ID is the to do with id2 the second record here I will hit the end point okay we don't have our controller method so let's add that out of head over to here let's have at Ash is that what we are calling here put okay let's use put let's call it update and this should be update we need ID and that is going to be in our part so we say put colon ID here we grab the ID which adds param IDE a of type number and down here we see ID and then the detail I will save that and try to call the endpoint again so we get the update successful now if I refresh this for item number two our update has been performed now let's do another step which is to delete a record to delete a record this time let me start from the controller I'm going to have a delete that will take the ID and text no request body let's call it delete and we are going to have a method delete in the service class so in the service class let me reuse this guy delete which takes and down here I want to just say I think remove yeah remove so there are different type of item syntaxes that you can decide not to fetch the record before performing an action on it so this will remove the record let me go back here I think I have an error not an error just so let's try the delete I'm going to add another record okay the server is down start the server I'm going to add another record with ID3 and over here we can see the item with ID3 and what I want to do here is to delete that record so we get a response why did we get any response at all delete let me see I was assuming that this should return something else instead of the okay so let's try to fetch the record again we can see that item with ID3 is gone alright guys this completes our crowd operation and since we said we're going to cover in this lesson let me just quickly recap the some of the key points that we have covered so we have created we created a project and next project using the CLI and then we configured our type orm module in the app module here we are connecting to mySQL database using these credentials the credentials are located in the dot EMV file which we are able to make use of in the configuration using the config module that nest.js provided provides and here we want to instead of listing out all the entities which is an option we want to automatically discover the entity files using some specified pythons and we said that you should never use this in a real project but because the migration is out of the scope of this tutorial so we are making use of this synchronize set to true you can set it to false or remove it entirely which is the default but for the purpose of this demonstration we are making use of this synchronize set to true and then we have seen how to create an entity we said that entity is what is going to be represented in our database tables for this example we have only to those if we have another one let me quickly add or more let's call that um category category doesn't matter let's call it anything and here I can say category and let me remove the the name so that type 1 will automatically generate it let's just have anything here then we say that when we have an entity we have to list them out in the module of Interest so in this module I'm going to have another entity called category then when I run when I start the server again we are going to have all those entities created according to the mapping that we are using here wait for the server to start go to the database and refresh you can see that we have category in addition to introduce then we moved on to perform some crude operations as we have seen in the in the to-do service in the controller we inject the repository that we we are in for the entity we are interested in and we can begin to make use of what type orn provides once again you can take a look at the type orm documentation to Learn Type orm syntaxes all right guys this wraps it up I hope it makes sense until next time happy coding [Music]
Info
Channel: ZestMade
Views: 10,847
Rating: undefined out of 5
Keywords: nestjs, typeorm, crud, mysql, REST api, nodejs, database, ORM, Nest, nestjs-crud example, nestjs crud, mysql nestjs crud, nestjs crud-typeorm, nestjs crud postgresql
Id: dAy4TZXzZck
Channel Id: undefined
Length: 42min 8sec (2528 seconds)
Published: Wed May 17 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.