Nestjs PostgreSQL CRUD REST API Example with Typeorm

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this next J tutorial we are going to connect to postr database and build rest API for Crow operations that is API for create the one for read update and delete this lesson assumes that you already know at least the very basics of next JS and that you have a postra database ready to be connected to so I'll start by creating a new Nest application I'm going to use Nest CLI and say Nest new you can call this anything let me call my PG C and then I wait okay I'll select uh package manager and wait for the installation to complete the project has been created so let me see it into the project folder C the next thing I want to do is to install some dependencies we need for this demonstration because we're going to connect to database we're going to make use of typ M which is quite popular in njs world and postgress um Library I'll go ahead and copy this command here which is npm command to install this type RM libraries I'm not going to copy my SQL because you're making use of postgress so let me just copy this and add the one for postgress npm install typm dependencies and PG for postgress database and in addition to that I want to keep the credentials for connecting to database in a EMV file for that I'm going to make use of njs config module I'm going to install the dependency as well for the config module so head over to the terminal and I we enter the command to install the config module dependency all right with all those installation in place let's head over and start writing some code now I have the project open in vs code the first thing I need to do the first thing I want to do is to do the configuration for the config module and type orm so I'll go to app. module. TS over here I want to import the config module Library so I'm going to say config config modu for root with this import import here it is expecting that there's a file at the root called EMV so I'm going to create that file dot EMV at the root the next thing I want to do is to import and configure type orm so I'll say type omm module. for root or for root as sync so for root a sync inside here let me import the config module so it is available within this configuration I will import config modu and inject the config service config service this one I can make use of the config service to access the information in EMV file and finally use Factory use Factory config service not that config service config service all right so here we specify the type of database we are connecting to in this case it is a postgress database so I select postgress the next thing are the connection credentials right so this is going to be the host I'm going to put all those values in the EMV file so I can use the config service to read the values from EMV file I say config service. getet this is going to be a string and the name let me just give it DB host for the host name let me copy this a bunch of times for other variable p a bunch of times then the next one the port for the database connection so I'm going to put a plus here because this supposed to be a number not a string I'm going to call it DB Port Port command and then we have the username for connecting to database so let me call DB user name in capital letter usern name and then password let's call ITB password and the database name DB let's call this name database name what we have so far are the information needed to connect to the postgress database but after connecting into the database I want to I want to create the tables and maybe update table etc for that I want to tell type orm we have to find the entity files that are going to be used to create the tables you can do this a different way in different ways so let me show you the first one is to list out the entity files for example the user class if we are going to create a user class that is decorated with entity we are going to create entity in a moment another solution is to give it a pattern where to find the entity files for example p. join process. current work directory and this is going to be in the dist folder so in this slash whatever slash the F that ends with entity. JS end .js so this is saying if you go into the this folder whatever folder all the file that end with entity. JS that is this entity. JS should be treated as entities file use that information for communicating with database and Performing whatever database operations one more thing I want to add here is something you should not use use in real project but because migration is outside the scope of this tutorial I'm going to make use of it so do not use synchronize true in real project so I'm going to say synchronize true this is going to look at the entity files and use the information there to create or update the tables in the database that is what this does you see how dangerous it is for example if you make a change in the entity file it might delete some things in your database whatever so this is advised against in production or in re project all right so now I have this information I need to connect to database but I will go over to EMV file now and provide the actual values for these variables so I'll go back to EMV file the first value here is going to be local host or 127.0.0.1 that is for DB host and then we have DB Port let me copy from here DB Port command this is going to be 54 32 and then the username here you provide the your username in fact everything here you provide your own credentials so my username is Dev and for the password my password is secret finally the name of the database you you are selecting to connect to so I have a database called demo that is database I want to connect all right I think our database connection information is complete now I'm going to create the entity and the associated files using the CLI for that I'm going to say next generate resource resource is going to create both the entity file the controller the service and the module and also add the module in app modu so for this I'm going to call it cities nextest G resources cities and I'll hit enter it's going to ask me whether I want to use graphql or rest or whatever I'm going to select rest going to ask me whether to generate the crow files just some template nothing much happening in those files so I will wait for the files to be generated here you can see the file is being that is created going to create the controller and the service class and some Dil for create an update and also configure that in app module okay so I will go over to the files let's see what is inside there before we continue this is cities and we have the entity class we are going to come back to this file there's nothing inside there and then we have the dto we have both for create and update and we have the cities modu everything inside this folder is generated by that command ra um next generate resource then we have the controller we have the service just on dummy content we're going to substitute for with our own code and finally that was wired up in it was imported in app module okay I will start from the entities file for this to be recognized by type urm as entity file we say at entity here you can you can give it a different name if you want to I mean the table Name by default it's going to be name of the class but let me give it a different name called cities this is going to be the table name we see in the database inside here I want to have the fields that will represent the columns in the city's table in the database the first one is going to to be the ID column this is going to be the primary key Auto increment column field so this is going to be a number a number and The Decorator we use to tell type urm about that is primary column primary generated column the next one let me have a field for name of the city so this is going to be name of the city and for the database we tell type this is going to be a column in the in the city table you can customize this folder for example we can say that the city name has to be unique there are other options then the next one let me have description for cities this is going to be a string come on string and we Al say that it's is going to be a column with type this is not going this is going to be a text type so this is going to be text in addition to being of type text unlike this one that is vaka vasha whatever I also want this to be optional so I also want this to be no level so you can say no LEL true next um I think this is okay but let me just add one more thing here like a different type of column let me say active I don't know if that makes sense here this is going to be a Boolean let me add column here column type Boolean I think that's supported in post gr and let's have a default value this is option maybe false or true anything okay so these are the fields for the entity file now all these all these fields are going to be created in the table called cities in the database by type urm to make sure that actually works let me go ahead now and start the server and check the database so npm run start Dev before that let me check database psql um database is demo let me check right now there are no there's nothing inside the database called demo so I'm going to start the server and check the database again wait for that to start now the application is up and running let me see if the table yeah so we have the table cities and if you check the columns you can see that it has those columns we specified I think I'm missing something here okay I think the command is deep uh deep plus and then the table name as you can see we have the the those columns we defined in the entity file and we with the help of synchronized through the table is created automatically along with the The Columns we have the name description active along with the the type of data that they hold now I will go over to the service class and replace this autogenerated code with the actual code for the crow operations at the very top I will have the Constructor inside this Constructor I want to inject the type repository for City so I can say private read only um let's call the city repository and we say repository this is imported from type orm for type City just like that but at the top of it we say at inject repository also from type orm of type city with the city's repository let me come down and create a city so const City to be equal to this do cities repository dot create and then I pass the C City dto but this C City dto right now has no Fields inside it let me go to the file inside this class we are going to list out the fields we expecting when the client sends a request to create a city we're going to expect name which will be a string and description this is optional it is also a string finally the active which is a Boolean so these are the three Fields remember that the ID field is autogenerated so we are not expecting that also for this D I'm not going to do validations that can be for a different topic different lesson so this is the dto for cre City and over here we use that and call create with the repository finally we can say con C to be equal to or let me just return in on this line our wait so this is going to be sing I wait this do City repository do save at this line this city is not saved to the database yet but we have to call save to save it in the city's table let should I think oh come on what am I doing then for find all this is going to be straightforward we we are just returning all the cities in the in the database so I'm going to say this is also sing going to say a wait this do c repository dot find and then for find one that is to find a city by the ID I'm going to also do in one line going to say this is also a sync so I'm going to say a wait this cities repository. find one but we want to find one by ID so I'm going to say where ID equals the ID that is supplied that is this ID here then for update I'm going to reuse this find one to First find the city so I'm going to say City to be equal to a weight so once again this has to be snc I wait this do find one and then Supply the ID but if the city is not found if no City found found I think at this point is okay to throw an exception because we cannot edit a city that is no that is not found I'm going to throw a not found exception here not found exception what is going on okay so I'm going to say new not found exception however if the city is found let me I'll just do object do assign the city and then the update City D so I'm going to kind of merge the two with this one overwriting Whatever that is here finally I'm going to await this do cities repository do save to save the updated City information and then the last method here is to remove a city so I'm going to do going to copy this the code to find a city or throw a 404 if it's not found but if it is found I'm going to return say await this do C's repository dot remove what do I want to remove the city okay so here we have the all the methods for the crow operation for create this two for read that is to fish data and this is for update finally we have one for delete the CLI command we run before also autogenerated the the controller with some default that makes sense for example this is to create it takes the city cre City dto and calls the service method for cre City you can see that in the Constructor we already have the city service injected and then we have the one for find all find One update and delete all thanks to the CLI for generating the codes now I can head over to the to the rest client in this case I'm using Postman and send off the request to for the crow operations the first one is to create a city so my Ur is Local Host 3000 SL cities as you can see from the controller this is prefix with cities now let me go ahead and send the request to create a city something went wrong let me check the terminal so the problem is coming from um Ci's modu the type orm repository we have here we have in the service not here we need to go to City's module and tell it to import type orm for for City repository to do that you go to the modu and say import inside here we say type orm module. for fure and then I have an array inside the array I'm going to list all the entities used in the services in the providers right now what I have is for City so I'm just going to say say City here and that should solve the problem let me check the console now now the dependencies and stuff are resolved I will try to create the city Again by sending the request this time it was successful we created a city let me quickly test out the other end point let me add another city um let's say New York 2 and add another one I don't know just put something there so I have have three cities created now let me call the endpoint to fetch the cities you can see we have the list of the three cities and to find one by the ID for example the ID one this should return the New York City which was the first one to update um right now the status is false for City with ID one let me change that to through you can see we get through and if I find it again the result is true and for delete let me me delete the second city that is New York 2 that is deleted if I call find on now this record should be deleted all right guys we have seen how to connect to postra database in nestjs and perform C operation before I wrap this up let me quickly show you what I mentioned at the early stage so I said that here you can just list out the the entities right now I have the city entity only that if I save this and try the operations again it's just going to work the same I don't need to restart the server but let me just restart that so I'm going to call the end point for example to find cities you can see that it works the same but for benefit of Doubt let's do some kind of negative testing whereby we break this without listing anything in the in the array so I'm going to to check the the application start again but let me go to postman and send off a request you can see we have an error right the application started because I mean in the array it can be zero or more list of uh entities so if it's zero it means there's no table we intend to interact with but you can see that the application crashed because you cannot find information about City but if I restore that and the application starts again and I send the request you can see that that works again so we are free to choose whatever approach you prefer whether you want to list out all the entities here or you want to provide a pattern like we've seen before all right guys this brings us to the end of this lesson I hope it makes sense until next time enjoy coding
Info
Channel: ZestMade
Views: 3,015
Rating: undefined out of 5
Keywords: nestjs/typeorm postgres, Nestjs postgres example, Nestjs postgres tutorial, Nestjs postgres CRUD, nestjs PostgreSQL REST API, nestjs PostgreSQL, nestjs postgres
Id: pI9C7NH4K5c
Channel Id: undefined
Length: 25min 56sec (1556 seconds)
Published: Sat Oct 21 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.