Prisma and Typescript - Full Course (2022)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody if you're using node.js you know that node.js works with some great RM libraries such as sqlize type program and Prisma and today we're going to talk about Prisma since it is currently one of the most used RMS and it is good to know more about it for explaining Prisma you may ask yourself why do you even need orange well let's say you need to create a user and you know what that user consists of for example first name last name email Etc since we are using node.js and node.js is built on JavaScript if you want to store this user in JavaScript you will lose objects but if you want to store this user permanently database you will need something to connect your application to the database itself that something is om an RM system will help you do that one more reason why I'm making this video is to see how the easiest to build crud application using node.js typescript and Prisma and what benefits we have from using in this video we are going to talk about Prisma schemas automatically changes from Models into database or to preview data model UI how to make indexes in order to make your queries faster what type of SQL relationships Prisma supports and at the end we're going to see how it is easy to make crowd application using node.js expressjs typescript and Prisma so without further Ado let's start with the video provides an abstraction that allows us to write database queries using JavaScript or typescript Prisma then Maps the queries written or a chosen language into the database of our choice which makes it easier for developers because we don't have to write queries in the database language itself Prisma is built on so-called object oriented paradigm currently Prisma supports MySQL sqlite post girl scroll SQL Server amongodb one of the primary reasons why prism is so popular these days is because it consists of three major tools first of all we have Prisma Clan JS which is a type safe and auto generated database Clan it is a so-called RM replacement second of all we have Prisma migraine which is a declarative migration system with custom workloads the last one is Prisma Studio it's a modern admin UI to support various database workflows let's break it down Prisma clean like I mentioned previously is a typesafe database client that replaces traditional RMS such as sqlized bookshelf and Mongoose it allows us to access the database through playing JavaScript methods and objects without having to write the query in the database language itself this is the part that actually acts as an abstraction in front of the database so it's much much easier to write Cloud applications Prisma Margaret on the other hand is a powerful database schema migration tool it uses a declarative data model in syntax to describe our database schema Prisma migrate stores our entire migration history and easily lets a revert and approve play migrations it also allows us to run before and after hooks to execute scripts while migrating so basically we can populate the database with required values during immigration Prisma Studio allows us to visualize data via an admin UI here we can perform crowd operations on our data this is the easiest way to visualize data from our database as well as manipulating okay let's install Prisma but before we install Prisma and all of the necessary dependencies we'll need to set up the node.js typescript starter project here I am in a visual studio code and I'm going to open a new terminal by clicking on a new terminal before this part also create a new folder where you will do all the work I have already done done and it's called prismacran we'll set up the project package.json and add the dependencies using the Y flag when creating a package using we simply approve all the defaults we're first going to add all of the depth dependencies typescript is going to be added as a Dev dependency and we are going to add one more dependency called TS node depth again as a Dev dependency TS node Dev is basically a package for node.js that restarts node server when any of the required files changes but its shares typescript compilation process between restarts and this significantly increases the speed of restarting server comparing for example to nodemon and TS node variations let's install those dependencies so we are going to install them by running this command MP uninstall typescript yes node Tab and like I mentioned previously we're going to distort them as a Dev dependencies as you can see here we added them as a Dev dependency after we install typescript we get access to the common light typescript compiler through the TCT command but more on that later on I'm going to install Express as a dependency also because we will need Express to run our server as you can see here we installed Express as a dependency not only as a Dev dependency since we are using node and X plus it would be good if you could get type safety and after completion on the Node and express apis like file path process servers and many more that's what installing the definitely typed type definition for node and experts will do well how to do that we are just going to run this command npm install at types slash node and add types slash Express but again we only need this on our Dev environment so we're going to install them as adapt dependencies next up we'll need tsconfig.json file the tsconfig.json file is where we Define the typescript compiler options we can create the TS config file by running the following command MPX TCT slash slash edit this is just a flag which is going to initialize ideas config.json file if you have installed TCT as a global dependency then you do not need MPX in front of it but I haven't do that so I will use it here let's press enter at this point you should have a TS config.json file that looks like this as you can see here we have a compiler option objects and inside this object we have a tons of fields that we're going to change we can go ahead and claim the commented out stuff that we don't need RTS config.json file should look like this okay let me explain this Roots there this is where typescript looks for our code we have configured it to look into the source folder that's where we will write our typescript out there or out directory this is where typescript puts our compile code we want it to go to a build folder es module internal this is a complicated topic and it basically requires much longer discussion and so if you are using common jss our module system for node application we should be then we need this to be set to true sold Json module if we are using Json in this project this option allows typescript to use it we are not going to use Json but let's leave it here lib and this option adds ambient type style project allowing us to rely on features from different Xmas script versions for example testing libraries and even the browser Dom API we would like to utilize some es6 language features but this all gets compiled down to es5 at typescript builds it module module command JS is a standard non-module system and we are going to leave it here no implicit any basically in types of files we do not allow our type to be unexplicitly specified every type needs to either have a specific type or be explosively declared any and that's why we need it here inside the script objects in packages and we're going to add a new comments let's delete this and let's write our own comment which is going to be Stark Dev this comment is going to be run by tsnodev and we're going to add another command which is going to be called build okay let me explain this I'm adding the start Dev command to start our server and also restart it if there are any changes on required files next to command yes no Dev I am adding as you can see two flags one is uh respawn another one is transpile only respawn which is required an additional transparent only which is good to use for large code bases and basically it will speed up things greatly this last argument to this command DS no Dev is the file we are pointing to basically the file which server is will be run on and our server will be run on the file server.ds which is going to be in the folder Source command build will only run the typescript compiler which is going to build our project in out directory which we specified here okay next step inside the script object in packet Json we're going to add a new comments we're going first we're going to delete the command test and add the comment start that this comment will be run by the PS no Dev package which has two flags one is respawn and one is transpiled only and we're going to add a also a last command which is going to be called build and it's going to be run by the typescript compiler okay let me explain this I'm adding star Dev comment to start our server and to also restart it if there are any changes and required files next to command yes no Dev I'm adding two flags respawn which is required an additional transparently which is good to use for large code bases and will still and basically speed up things greatly this last argument to this command is the file we are pointing to which server will be run on our server will be run on the file server that yes and this server.ts file will be in the source folder comment build will only run the types compiler which is going to build our project in my directory that we previously described in tsconfig.json file okay let's test it everything works like it should should create a new folder called source and inside this folder we should create a file called server TS let me make that and let me make a file called server TS inside this file let's for example console log something hello world and now we should run our Command from the package.json which is start Tab and to run command from the scripts object inside packages and we write first npm run and then name of the command to start that and as you can see here everything works fine we have console logged hello world in our terminal okay let's set up Prisma first we need to install Prisma as a Dev dependency previously we used to install prism as a global dependency but that is not recommended anymore let's write npm install Prisma slash save that and run the command okay as you can see the Prisma has been installed as a Dev dependency now in order to initialize a Prisma project in our directory we should use the following command and fix Prisma in it and there is an additional flag which is called data source provider that the source provider flag is not necessary but it will speed up things for setting up the Prisma if you are using any other database just write that instead of SQL live which I'm going to write for example you can write MySQL or pause gear SQL or SQL Server whatever let's press enter and now as you can see we have a new folder and a new schema that Prisma file inside that folder okay go ahead and remove all of the comments and change the contents of schema.pism to the following first we're going to delete all of the comments because we don't need them and beneath the data source block we're going to paste the two new models now let's break it down here the schema that Prisma file contains data model as well as the configuration options but before we do anything else here I would advise you to install Prisma extensions inside the visual studio code called Prisma this adds syntax highlighting linting code completion formatting chapter definition and more for Prisma schema files the data source block is used to specify the connection to the database we set the provider field here to sqlite basically sqlite is embedded database software that can be used anywhere it allows us to create a local database without having to install anything oral fill contains the connection string to our database here we can either choose to type the connection string which will be seen by everyone or to use a better approach which is in environment variables like it how to be has been using by specifying the data source flag when initializing the project Prisma project as you can see here when we use the data source provider flag Prisma will by default create the dot EnV file whatever we type after the file here is the name which the database gets created in our case the database will be created in the Prisma folder with the name not Dev but the bit.db let's save the environment file generator block by adding the generator block we specify that we want to generate prisma's database client this client is generated by running the Prisma generate command and will be located in the node modules at Prisma we are not going to open that right now and it can be imported as import Prisma Clan from at Prisma slash client we're going to see that later on here we have two models modern so-called model blocks here we Define the user data model using the mod unlock models represent the entities of our application domain basically on a technical level a model maps to underlining structures of the data source for example in relational databases such as sqlite and pausing SQL or MySQL model maps.table there is an annual relational databases for example mongodb you have to map to a certain collection uh here inside the model user we have a three attributes namely ID first name and last name the the ID field is a primary key of A type string where I'm going to explain much later on but this tree here attributes means but let me just break down the middle of user in general the ID field is a primary key of A type string with a different value of collision resistant IDs my advice to you is to use this instead of using any other IDs because Collision resistant IDs are optimized for a horizontal scaling and binary search lookup performance basically better performance acquiring your database overall to determine which field of a model is a ID we can annotate it with using at ID attribute we will talk about that chargeables like I mentioned previously in that annotation later so do not worry about these things right now here the first name and last name field is a type of string finally we Define the car model the car model contains four Fields first one basically any model needs ID and car also has ID it has color which is a type of string it has both which is a type of Boolean and it's a default value is false and name which is a type of string now to add Prisma client to the project and to utilize everything that Prisma offers we need to use the npm and to install it we can use the npm command npm install at Prisma client in order to generate the Prisma client we also need to type another following command which is MPX Prisma generate and as you can see here you can now start using Prisma client in our code and this is the code that I also mentioned previously about how we can import Prisma Clan one more super important thing to mention if you didn't have any models here and we run the MPX Prisma generate command it would fail because we couldn't generate anything so basically when we type the command npx Prisma generate that comment will look our schema that Prisma file and it will see what models we have and on those models it will create types methods and Etc you will see that later on so basically if you want to generate bismacklan please make sure the first create models and then run the command and picks Prisma generally now let's talk about how Prisma hand was the relations inside the escalator relation databases such as the sqlite first let's open the schema.bism file and check on all the build car model and already built model user for our application let's say each user is supposed to optionally have one car and each car must have one and only one user this is called one-to-one relations in SQL first let's create a one-to-one mapping between the two models inside the model user we're going to create a new field called car which is going to be of type car the question mark at the end denotes an optional vulnerable field we will see later now when we do migration but this means on one side of this relation we must add ID field for referencing because in reality only makes sense to First create a user entry and then link a card to it we'll add a user field inside the model car and add the relation attribute again in a model car so we finish with the model user we created the car which is going to be a type of car and that's it and if you hover over it the problem as you can see the relational field car model user is missing an opposite relation of your model car that's why we need to create a two new Fields here first field is going to be like I mentioned previously user ID which is going to be for type string and the relational attribute to write relational attribute press type the name of a field then the type and the relational attribute starts with at relation now hitting the control space in es code will give us some hints as what we can put in here the first thing we'll need is the fields on this car model we want to use for mapping this is going to be our user ID field that we just created this user ID field is also called relational Scuttle field so let's press here fields and inside this array just type user ID and comma the second thing here is the unique field on the other side of relation our other side of relation is this model user and the only unique field here is the ID because uh one user can only have one specific ID so let's type the references and add ID but again as you can see we still have an error in this case we need to mark this field user ID with the unique attribute to guarantee that there is only a single user connected to each car so let's add that and we fixed all of our errors we are going to talk about later on with the data attribution data notation regarding the at unique at default and Etc so don't worry about that okay let's talk about now one too many relations in our application user can create car blocks on this application so let's create a new model for car blocks with a creation timestamp and add a list called car blocks on the user model to create the relations between them okay let's create model car blocks and inside model Cloud blocks let's type the ID I'm going to delete everything else here but thank you guitar palette and I'm going to type a field string on content of a type string and the last is greater that which is a type of date time and the default value is now let's save it now inside the model user we're going to add a new field which is going to be of a car blocks and a type car block I forgot to mention here let's leave it like this and again we have the same problem as we had previously so inside the car block we're going to add a user ID for type string and again the user uh field uh relation attribute with the type of user and that's it in order to explain one-to-many relation properly this array modifier here marks the field as a list so this means that the user can have many blocks created about cars and that specific card block can only have one user many to many relations refer to relations with zero or more records on one side of the relation can be connected to zero more records on the other side and relational databases many to many relations are modeled via relational tables here in Prisma many to many can be created either explicit or implicit way uh in an explicit menu to many relations the relational table is represented as a new model completely in the Prisma schema and can be used in queries when fetching the data from the database acquisite many to many relations basically Define three models two models that have a many-to-many relation such as car block and we will going to create a new model called category car block and also there is a third model that represents the relational table such as categories on the color blocks also sometimes called the pivot table in the underlining database so let's make up a new situation to say that our call blocks model can have a multiple categories inside and that multiple categories can also have multiple blocks assigned to that specific category this is a basic system of text that you could see on any social network for example we're now going to create a new model and also we need to change already existing model in order for this to work so let's do that as you can see here in inside the model cardboard we created a new field called categories of a type categories on car blocks which needs to be type of array and inside the category car blocks we also created a new field called car blocks which is going to be of a type again categories on a car blocks array and we created a completely new model categories on car blocks ID annotation attack identation is used to define IDs and it is super important to edit inside this new pivot table to make it work why is it called the pivot table well we have the two IDs from the two models that we want to connect and how to connect all of these three models well inside this pivot table you need to have like I mentioned on the IDS and as you can see previously in prisman I explained in order to connect two models you need the at relation attribute and you also need the ID which is going to be used here inside the fields and that carb load ID for example here is going to reference the ID from the car blog model that's why it needs to be of a type string because this is a type of string if you put here in it will not work first we will going to have an error here and then we're going to error we're going to have another error here so that's why we're going to stick to the string because it works and again we add it as the same the new ID but this time we are not uh referencing the ID from the car block instead we are referencing to the category car blocks and these are the two important Fields inside this model the optional Fields you can add whatever you want I added a signed ad which is a type of date time and I added assigned by which is a type of string now here the at that ID annotation is used to define IDs and it is super important to edit inside this new pivot table to make this many to many explicit relation to work implicit many to many relations are much easier to understand and they Define relational Fields as arrays on both sides of the models although the relational table exists in the database also called the pivot table it is not managed by us it is managed by Prisma and does not manifest in the Prisma schema so we are not creating it inputs it many to many relations makes the prismaclint API for many to many Innovations a bit simpler so now we are going to create a new fields and they need to be a type of array like I mentioned it so inside the car block model we're going to create a new field of a type categories and it's going to be of a type category car plugs and it's a type of array and then inside the category card blocks we need to add another field which is going to be of type cardboard and there you go as you can see here it is much much much simpler to use implicit menu to many relations and I would advise you to use this instead of using the acquisite many to many relations a relational field can also reference its own model in this case the relation is then called a software relation software relations can be of any cardinality one to one one to many and many too many know that soft relations always require the add relation attribute I'm going to add two new Fields inside the user model let's add friend for type user and a question mark to make it optional enrollable and add relation attribute also inside the add relational attribute you can add a custom name so basically the Prisma we're going to create a custom name for us but you can change that custom Name by first before adding the fields and the references you can add a string here which is going to be a custom name for our relation let's add here friend and now let's type uh before this I'm going to add a free and friend ID of a type string and I'm going to make it optional I'm going to explain it probably needs to be optional and also I'm going to add it to be a unique field now and so let's get back right here inside the field survey I'm going to add a friend ID which is going to reference the ID here and also let's add one more field it's going to be a type of friend-off and again user optional field at relationalfriend okay this relation X pluses the following a user can have one or zero friend of for example John is a friend of Jane and user can have one or zero friend for example John is James friend one-to-one soft relations cannot be required on both sides so if I put if I delete the optional Mark here this is going to fail this will not work so I need to add it on one or both sides must be optional otherwise like I said it becomes impossible to create the first user record to create a one-to-one solve relation there are a few steps a part of the side of relation must Define at relation attribute to share the same name like I mentioned previously you can create a custom name and this is the custom name in this case it's friend one relation must be fully annotated in this case it's a friend one relation must be packed by Foreign key The Front Field is backed by Foreign key and this is the friend ID which reference a value in the ID field the friend ID field also requests at unique attribute to guarantee a one-to-one relation if you do not put this here there will be errors when trying to get the data from it one more thing to mention there is another parameter to The annotation at a relational uh attribute which is called referential actions they determine what happens to record when your application deletes or updates a related record in the following uh in the following example adding on the lead Cascade to the car blog user field means that deleting the user record will also delete all the related car blocks relating to that user so let's add that we're going to add undelete Cascade and that's it we finish with talking about types of relations inside the Prisma if you did not understand it properly please let me know down in the comments below also Prisma documentation is a good place to learn more stuff about not only relations but Prisma in general fields in Prisma are really important to understand properties of a model is called field and in most cases increasing stuff a field name must start with a letter and in most cases it is spelled in camel case a field type optional type modifiers and optional attributes including native database type attributes a Fields type 10 minutes structure and fits in one of the two categories as color types including enums that map to columns or a document fields in the database for example string and pulling Pig in them anymore model types the field is then called relational field as you can see here for example car block or call block array and Etc as the Prisma documentation says attributes modify the behavior of fields or model blocks so you can basically change what certain field in the model does fields are equivalent to columns in SQL databases some attributes will lead Arguments for example at default exception argument which can be whatever the type of the field is in this case if it is a string we can Define the default value to be whatever string we want if it's a type of Boolean we can either be the default value can either be true or false and Etc and something to mention is that we can Define also functions as a argument which will return the value such as constraint resistant IDs function and auto increment function for specifically IDs while we are on a topic of an ID what's an ID in the database an ideally identifies records of a model inside the database for example there can be only a single car with a specific ID in relational databases the ID can be a single field width or based on a multiple Fields if a model does not have an at ID data notation or an at idea dat annotation we will see that later you must Define a mandatory at unique field or add that unique block instead in the following example the car ID is represented by the ID string field this means that the car will be uniquely identified by the single field ID but there is a thing called composite ID which means that the model will be represented for example here by combination of the fields for example we can make it to be at that ID type name and column but if you do decide to use composite IDs then you do need to delete this here and as you can see here everything works perfectly fine you do not need to use the ID annotation like I mentioned it previously you can choose a at unique field for defining unitified records but if you do up to using this which I do not recommend you will then need to make that field non-nullable otherwise it will not work so inside this model car I want to make this color string an ID with ADD unique data notation so let me just type at unique one thing to mention you cannot use the foreign key ID as the primary key ID if there can only be one foreign key or one primary key you can Define default values for scalar fields of your models using the app default attribute default values can be static values that correspond to the field type such as 5 for INT hello for string or false like we have here for Boolean we can also use list of static values such as 5 6 8 for enter a of a type or hello goodbye for string array type these are available in versions for that point O and later and in databases that support list value such as postgresql will not be using these because it will not work on sqlite and we can also use functions such as 2id or now you can add unique attributes to your models to be able to uniquely identify individual records of that model we already explained the unique attributes and they can be defined on a single field using that unit attribute or on a multiple fields which if you do remember is a called a composite field using the at that unique field so inside here let's add the attack unique field for the first name and last name you can also Define indexes on one or multiple fields of your models via the attack index on a model or at index for a single field and accessing databases are really really important if you do have problems with performances Prisma will not create a sloppy query if you do think that but sometimes you will need to use indexes especially if you query the data by a specific field we do not need to add the index and primary key because that base itself will do that for you again you can add it on a single field or create a composite field and in order to show you how to create an index you just type the at index here and just for example choose fname and that's it you can even create a composite index for example we can add the left name BNB L name and we can name these things as index for example the F name and the file name combination which is my so powerful that you can Define enums in your data model if enums are supported either natively or at Prisma level you will often use enums if you for example are making authorization and authentication functionality and especially if you're in need of a rules for a specific user we can create a new enum for example Raw and inside here we can create the admin and user field and inside the model user we will create a role of a type role and the default value will be user if you paid attention to what I was saying throughout this video you could hear me talking about scalar Fields there are tons of color Fields supported by the Prisma at the front of the most used are string pulling and begin to float that's Mount Json Etc if you for example write string as a field type Prisma will map the string to the native database type attribute in this case string will be mapped to a text field if you do want to specifically map the field type to the native database type attribute you can do that by typing the following annotation for example first name is a type of string but we can type it to anything we want for example DB that bar chart 255 this would work but native Type R chart is unfortunately not supported for sqlite connector if you do want to search more about how you can map the different color fields to a different Native data type attributes then you can check the description down below and there will be a link to a Prisma schema API for the reference benefits from using this is that you can then control the exact native type that please by migrade creates in databases last thing to mention is type modifier but we already touched this topic earlier the type of a field can be modified by pending either two of modifiers make a filter list if you're using array or make a field optional you cannot combine these two type modifiers optional lists are not supported correctly we create a new model today and it is time now to migrate these changes using the super powerful Prisma migraine in order to migrate the changes from the schema that Prisma file to the database you can type the following command MPX Prisma migrate path when you type this command and wait for a little bit you will be prompted to enter the name for this migration please when you are typing the name make sure the name for the migration is long enough to understand it for this demo purposes I'm going to call it first migration on that bit Channel there you go we created our migration and we successfully created our database let's show you how to migrate the model changes into database and I'll be mentioned about the Prisma Clan now it is time to show you how to add and see the date and model UI or graphical user interface open your terminal and add this command and text Prisma Studio we will now be able to open the studio which will be hosted in the port 5555 as you can see now we are able to see all of the models we created and the reason we open ones if you already opened Prisma Studio before click on whichever you like I will click on cover but important thing to mention here is that you need to do all of the migration before opening the studio once you have clicked on the certain model for example I click on the car there is a button with the label add record which will help us to create a new record very easily without making the files for saving purposes if you do want to make a file for saving purposes what you need to do is to inside your main folder in our case it's a source folder create a new file called seed yes or call it whatever you want and call copy the following code first we have imported the Prisma client from the Prisma at Prisma client package which was generated from a schema Prisma file when we run the MPX Prisma generate command next we create the constant called Prisma which is an instance of a Prisma plant we have an async function called Main and calling the main function if any error occurs the catch block will catch the errors and will display it in the cons of that error command and whether an error happens or not after the running the main function the code block inside finally will run so for example if I type here console log it starts seating for example inside the terminal then you need to install the following package called TS node and install it as a dependency then you can type the following command inside the terminal MPX yes node Source C dot DS or the name of your file for scene and that's it in Prisma Studio I've opened the user model and inside the user model now I'm going to create a new record in order to do that I'm going to click on ADD record button and now we need to type the values here inside the ID we do not need to type anything because we open the schema.pisma file and inside the model user as we can see we have the default value of collision resistant ID inside the first name we can for example type Dev last name fit car car is an optional field because we do not need to have a car as a user so we do not need to click anything here car blocks again this can be either the zero or whenever we create a new car block then we can add it inside here for an ID we do not need to have a friend again friend we do not need we do not need to be friend of anyone and friend off again same thing let's click save and change that's it we created a new file or a new entry to be more precise inside the database and the ID is Collision resistant ID now let's get back to the car model and I'm going to create a new car to just show you how this works whenever you have a foreign ID key inside the ID again we do not need to type anything here color can be blue both can be false because the default value is a false name can be Audi A5 and now inside here you cannot type anything here because we do not know the user ID especially if we are using the Collision resistant ID which is a string that has many characters and it's impossible to remember it so we can click on this user here and it will open a new tab or a new drop down menu and inside here we can select this here and we can open it in a new tab if we want but we do not need to do that I'm just showing you that so we can just collect the user here and that's it we can now click on save and you can click on crystal sorry click on the exit out of this menu and then click on save one change and that's it now we have a car now this user has a car as you can see here when we click on this it's connected to the oda file this has been a short crash course for Prisma if you do want me to create a completely fluid Fletch full stack application using Prisma where I will show you how to create a database that is scalable then make sure to comment down below it is now the time to create a simple crowd application and to see is it easy to make when using Prisma node.js and express.js this is not a tutorial on how to make the best rest API ever this is just a tutorial on how to use Prisma and node.js and Expos if you might need to make a real world project using Prisma node.js please let me know down in the comment section below also before we start I realized I made a mistake in showing the TS node tab package and command I accidentally undo the installing of the types for Express and node dependencies so please make sure to do that one more thing to add is another flag inside the TS node Dev command because I initially didn't want to focus on making a better structure of rest API in this video but I realize why not so that is why we need to add a new flag here which is called exit child this file this flag here is important because we're going to use multiple files and those files will act like children's to the main server.ts file and you will see why okay now we're going to create a new file called appds and we're going to create it inside the Source folder here we're going to create a new class which will have this structure okay let's save it then next we're going to use the already made server.ts file and we're going to import the this class here to this file let's do that we're going to import and we can name it whatever we want because we are exporting as this class as a default so let's name it app from app and here we're going to create a new server but first we need to use the port I'm going to press we need to create a port a variable for our part and then we can use the only build method inside the express JS which is called listen the first parameter to this function is the part and the next parameter is the Callback function that we can use to basically just write something to our terminal that this server is running on this part to explain how this works when we export the file we export it as a default account Dimension and we are automatically creating a new object whenever we export this file using the new keyboard and we are getting the public variable from this class called public serial server this public server variable is initialized in the Constructor every class needs to have a Constructor and inside our class we are initializing this public server variable to express method which is going to which is able to create us a new server and to basically use middle layers and everything that is important from the express JS package also we are initializing the methods middlewares and routes middlewares are important for the express JS application and here we're going to here we are using the all the built-in middleware from the Express package called express.json we need this package here in order to use the request.body inside our roads and controllers you will see that later on and here we have the method routes inside this method we are going to again use the use metal from the express to basically initialize and create a new routes but you're going to again see that later on as you can see now I have splitted the responsibility from the server.ts file to the app TS in general avoid the nasty habit of defining the entire Express app in a single huge file it is better to separate your experts definition to at least two files the API declaration which is going to be in our app file in a class app and some other stuff for example networking concerns for even better structure you can locate your API declaration within components but today will not do that okay now we're going to create a new folder called routes and we're going to create a new folder called Services inside the services we're going to create a new file called prisma.ds basically we're going to initialize the object from the prismaclan class here so we can use this subject wherever we like to use it in order to initialize it we you need to import the Prisma Clan class from the Prisma client package we can then initialize the object by using the new keyword the class and let's export it as a default so we can name it whatever you want when we are importing this variable here in another file okay that's done inside the roads folder we're going to make a new file called index TS but but I'm not going to use that file now and now we're going to create the three new files user that routes that TS we're going to create another file called car roots that yes and card blocks backgrounds.ps future debit here and I told you to make three routes file but you watch the video to the end you will see that I did not touch them besides the user that throws that DS file you may ask well what is the reason for this the reason is is that is the task for you I want you to watch the video to the end and make the exact same methods just for the different models not the user man and use the methods from the Prisma to just get better at remembering them and to be just better at the Prisma in general okay back to the video here inside the user that wrote the TS file we need to initialize the router from the express.js so we can make a new endpoints and basically just make a new route how to do that we need to import router from the express and then we need to create a new router or basically I'm just going to name it routes because it's easier for me and then on this variable here we are basically now which is a type of router we have a few methods when we Press Start and control space we have a method for get request post request and everything else we will use the get request because this first standpoint we are making is for getting all of the users from our database now the first parameter to this function get is basically the end point and I'm just going to name it here the Slash and you'll see later in our why and the second parameter is the Callback function which has two parameters request Handler and response Handler but I'm not going to do that here what I'm going to do next is create a new folder called controllers then inside this folder I'm going to create a user.controller.ps and here I'm going to export an object called user controller just making a JavaScript object and then thanks to GitHub pilot basically I can do this this is a method the same way for example I can do this what I did here I can do this in inside here but like I mentioned earlier it is better to separate things basically I'm making a function called index or a method inside an object which has two parameter one is request and one is response but we need to import the types for this so we can use this and also as you can see here we do not have a Prisma file but if you do remember we made the services folder and inside that we made a Prisma file so let's import Prisma now from the services.prisma and I'm going to explain this later on let me just finish making of user routes now inside the controllers we have a user.controller file and we bring to import user controller object because I export it as a const as you can see here that's why we need to use the curly braces and let's use the method called user controller.index well we made a new endpoint and a new route with the get request but how can we get this request or how can we access this endpoint first of all we need to import the user routes from user that routes but if I do not yes I haven't exported so let me do that we just need to export these routes and again if we I'm going to add a new routes inside this file but we will do that later on let's export this file user routes and now inside the app.ds we're going to import user from routes how do we make a use of our routes in this case user routes router module that we imported from the routes folder well inside the routes method in this class app we already have a server that use middleware which will help us do that we first need to specify the starting path for all of the routes inside the user.nodes that DS file so our starting flat will be API slash API users and now the second parameter means that when a user hits this route users the routes from the user routes file so that's provide this year will be run but depending on the method that user requests the end point with okay now in order to test it everything works perfectly fine we need to start our server in order to do that let's run the method npml start tab which is going to run our server as you can see Server is running on the port 3333 from the server.ps file and we created the port variable here if you do remember now in order to test our if our endpoints are working correctly I'm using insomnia insomnia is really really cool application for API testing and Etc if you do not like using insomnia then you can use Postman or Swagger or whatever you like I'm going to create a new HTTP request and I'm going to write our page URL which is http localhost and on the port 333 and now I'm going to hit the road API users and the request is going to be the get request let's click on send and as you can see here everything works perfectly fine now we wanted to explain this we are getting our user back we will get multiple users but since we are only have one user database we only get one user this is the case because inside the user that throws that TS file we are using the user controller that index method from the user.controller.ts file and inside this index method we are returning the user from the method prisma.user that find many and we are returning our user as in Json format in order to create a new user I'm going to create a new method inside the user control object that method is going to be async and it's going to be called create user again with two parameters request and response now inside this method I'm going to be using the request.body object request that but the object allows you to access data in a string or Json object from the client side and you're basically going to use the request that body object to receive data through post and put requests from the expert server I'm going to initialize the user data variable to use the request.buddy in order to create a new user we're going to use the prism object from the Prisma client class I'm going to type the const user await now the reason why we are awaiting the any method from the Prisma because Prisma that for example that user defend is going to return us the promise Prisma promise and in order JavaScript to get the value from the promise you need the at a weight keyword or you can use that 10 premises but I like the await async approach much better now when we type Prisma Dot and press Ctrl space you're now going to see our tons of options the most important options to us are the properties on the prism object these are the models that we created in our schema that Prisma file here so I'm just going to use the Prismatic user because we are just going to need it here that any other model when we type prismat.user dot again Ctrl space or command space you're now going to see a tons of new methods from the prism object in order to create a user we're going to use a create method discrete method here has tons of arguments to this method but the most important one is the data the reason why data is important because it is required now inside this data object when you again press Ctrl space you will now see again the properties not properties but like fields from the user module I'm not going to type the F name but the reason we are using the request that body is because we I'm not going to write anything static here for example that one because that would not make sense so I'm now going to use userdata that app name and the last required field in our model for a user is f a last name so again I'm going to type user that at this time I'll name now I'm ready to return this to user I'm going to just use the rest.json map code from the express server and I'm going to return the user object now as you can see here I only wrote fname and last name the reason why I didn't wrote anything else even though we had tons of more Fields inside here fields that are marked as optional we have default values we do not need to write them because you don't need to have a car because it's optional fuel car block is array I can either be of a value 0 or more and print ID is again optional and ID even though it's not optional it has default value of a collision resistant type so now let's check if this works but before that I created a new request which is hitting the endpoint slash API slash user slash create but I need to create that endpoint inside the user that routes the PS file I'm going to create a new route post slash create and user controller that create a user now inside here I'm going to click on this body drop down and click on Json and now inside the JS I'm going to type the first name to be for example the one and I'll name sorry project is this here is for example Bitcoin and that's it I'm going to save it with consent and as you can see here we created a new user of our ID first name last name and find the ID is a null value because it is optional and we didn't write anything in our create a user method we also have a select include uh arguments uh to select which properties or fields to include a return object and include means that we need to specify which relations should be loaded on return object even though include is an optional field if you do not write about relations we want to return plasma will not return as those properties in Json format or any other because we have to specify that and as you can see we only return the first name and last name and if I want to include something on that return object I just type the include here and for example I want to include a car like I mentioned just type include card true so let's create a new user for example that 2 and B2 send and now we have include car in our return object but we didn't create a user with the cars so that's why the value is known if you now go to get all users click on send we will now have a three users inside our return dungeon now in order to return a specific record from the database we can use the method called find unique but before that we will need to create a new method inside our user controller object again async find unique user which will have again request parameter and response parameter now inside here we just need to type you can either this method find unique we will return as a single database record either by ID or a unique attribute again here on the Prisma method we are going to use the property user and the method find unique this method has the previous one create again has some required arguments and this time you require a required parameter is the where and inside the rear we can either choose the ID or friend ID I'm going to use the ID but before that I'm going to get the params from the request cut params object and I'm going to get the ID so param ID and this ID is going to be equal to this param sorry it's going to be equal to this param ID and I'm going to return as a unique user using the rest.json method from the Express now inside the user that runs file I'm going to create a new route loads.get and I'm going to type just this which is going to dynamically get us the ID from the URL again I'm going to use a user control object and find unique user method so I decide we are going to create a new HTTP request but I'm also going to name it get unique now inside here uh I'm going to type the same well as in get all users but I'm going to copy the ID from one of the users for example that bit and inside this I'm going to just type this which is going to return us the unique user and I click on send now we have a unique user as a returned object one more thing to mention for example if I wrote here instead of ID for example user ID and I save it and I go to the insomnia and press send the server will not do nothing the reason for that is because in the find unique user method we use requested params.id instead of using the user ID I would also suggest to make a new folder for example models or types and type everything for the request.body and request.parms but in this case we're not going to use it because we do not need you already saw that in order to return all of the users we can just type the file menu method but inside the high menu method again we can use the rear object and inside here we can for example use the name field and that first name Bill for example needs to start with and let's say the d letter and inside get all users I'm going to send and we are going to return all of the users because all of our users have the first name as which starts with the letter D but for example if I change this here to b letter and press send you're going to blend a blank array for a array with no values inside it because none of our users have a name starting with letter B this means here that Prisma client supports filtering on a record fields and related Echo fields we can either return all of the users by a single field value or for example multiple field value what I mean by this let's delete the first name here and use the end property and inside this end I'm going to write that the first name needs to start with the letter d and last name means to end with number two so inside insomnia let's click on send as you can see we only return the second one because the first name starts with the letter b here and last name ends with uh book number two now in order to update a single record we can use the Prisma dot model in our case user that update the method but before that again let's make a new method now this method again has some required arguments in this case requirement is here because we need to update only a single letter record not many of them in our case the ID we are going to get the ID from the same way that we used in the find unique user soon to be param ID now the second requirement argument here is the date data property that we already seen before we need to update for example first name to be that view let's return to our user the updated user inside the rules there that routes that yes file we are going to create a new file is going to be have a put request and second parameter is going to be our function user control update user and I'm going to use the same ID as the before and inside our I forgot to mention I'm not going to use the static value here I'm again going to use the first name from the request that by the first name so sorry about that now inside the summary I'm going to create a new text which is going to be our type by Json and the first name I'm going to be the dev nope save it and change from get to put do not forget about that and click on send as you can see the Prisma returned us the updated user you can check that in get all users but before that let's delete this uh object that we created as argument and return all of the users click on send and as you can see the first name before was a dev1 now is a w the last thing I'm going to show you today is I'm going to delete a single record in order to delete a single record you will need to use the Prisma dot model in our case the user so Prisma that user the delete method but before that once again let's create and for the last time new method delete user inside this method again I'm using the requested params.id in order to delete only a specific user not multiple users and the required argument inside the delete method is again aware because we only want to delete a specific user like I mentioned not every user in San Antonio let's create a new HTTP request this new request is going to be of a type delete and again I'm going to use the same ID that we use for a updating user and getting a unique user from an ID but before that of course in the user that wrote that DS file you need to create a new route of a type delete hopefully you have learned how Prisma works and why it is so good to use as you can have seen throughout this video in order to make Cloud application you do not need a lot of knowledge and you can make one lesson than 13 minutes I didn't make all of the routes because this is not the point of the video the point was to show how Prisma works and how to make really really simple crowd application if you do want to see me make a full stack application where I will show you how to create records in one-to-many relationships inside them or many to many or self-relationships how to include them and many more things make sure to subscribe to see it in the future if you have learned something from me today please make sure to subscribe to the channel like the video and comment down below what else you want to see from me take care and goodbye take care and goodbye
Info
Channel: Samsk2
Views: 22,131
Rating: undefined out of 5
Keywords: prisma orm, prisma tutorial, react js, prisma io node.js, node.js, express.js, typescript, node js typescript, prisma typescript, prisma crash course, prisma crud, typescript node js crud, node js crash course, prizma.io, prisma.io pagination, prisma.io docs, prisma.io node editor, prisma database, prisma easy, prisma build, prisma build schema, prisma build client, database easy, source code prisma, prisma io node js
Id: NwL2nIrvTfk
Channel Id: undefined
Length: 66min 40sec (4000 seconds)
Published: Sun Nov 27 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.