Prisma 2 (Node JS ORM) Crash Course - 2021

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody welcome back to the channel in this crash course we are going to explore prisma now i am over here at the prisma.io landing page and it says that prisma is a next generation orm now what is an orm well an orm is an object relational mapper and essentially what it does is it really simplifies the way that we are going to query and mutate data and it does that because it allows us to mutate and query data in an object-oriented paradigm so let me kind of explain what i mean by that through this example over here so this is a really good example so let's say over here we have a table so this is a table of users so you can see here we have an id first name email and active and let's say we want to go ahead and we want to insert data into this particular table well to do that in typical sql we would have to create an insert into statement so we would have to go ahead and create insert into users table and we would have to supply it with the first name the email and then the active status now in in prisma we don't have to do that through the use of an orm it is actually a lot simpler so over here they actually kind of have an example of how this is going to be done through an orm like prisma so over here we're going to create a new record you can see here is going to be prisma.users.create and then over here data first name last name and then their email as well and then go ahead once once this is executed we go ahead and we find it now same thing with finding records instead of having select star from whatever you can go ahead and do something like user dot find many and you can go ahead and have your kind of conditional over here and there we go you find it and that really kind of simplifies the process really all it is trying to do is just making dealing with our database a lot easier so instead of using kind of complex sql statements we would use a more object oriented paragraph that most programmers are already comfortable with through the use of an rm like prisma now prism is a very special oram because it does a lot of different things so let's actually kind of explore what it does so this is one thing that it does another thing that it does is it allows us to model our data very very easily so instead of you know creating complex create tables and kind of relating tables together manually through foreign keys prisma makes that really really easy all you have to do is go ahead and create something like this you will have to this does kind of look very similar to sql but you know there is a little bit difference over here we have a an integer over here we are defining the type we're defining that it's an id but you can see here the the the true power of this is how we can actually relate data together you can see here that over here an author is related to the user and you can see here this is how we define a relationship between the two and it's it's really really a lot simpler and a lot cleaner than actually doing that manually through a sql create table statement so that is one thing that we can do and there's actually many many different things that that prisma can do for instance it allows us to migrate our schema to our database very easily it also allows us to introspect our our data into this schema over here so if we already have a predefined schema inside of our table we can actually introspect that and put it into the prism schema so if that doesn't make any sense to you don't worry we're going to look into that in a lot of detail and another thing that i really really like about prisma is that it allows us to actually visualize our data this is kind of something a feature that i haven't seen with any orm so prism actually provides us with a gui known as prisma studio and we can actually go ahead and visualize our data through that gui and we can actually go ahead and also insert and create an update which is which is really really cool can come really really handy now as you can see here there are supported languages so it really only supports typescript and javascript and typescript and go go is in early access and these are the databases that it supports so it really only supports um really only supports sql databases we have mysql postgres and sqlite we are going to be using mysql for this crash course just because it's a lot easier to get running on your local machine but you know the concepts that you learn here are going to translate very easily to postgres as well as sql lite if you want to use these databases all right so that is pretty much that if you want to learn more about prisma we'll continue watching this crash course and go ahead and read this documentation if you want to at prisma.io it's really really good uh but i'm gonna try my best to cover almost everything here so uh if you want to learn more about prisma well continue watching enough for the talking let's actually go on and set up our prisma project now to set up our prisma project i highly recommend following the docs that they have in prisma dot io so to do that all you have to do is you have to go to quick start right over here and let me quickly zoom in a little bit just to kind of increase the size of this so you can see here there's actually three ways you can really get started you can do a quick start using sequel light or you can add prisma to an existing project or you can start from scratch now in us we are going to start from scratch just so we have a good understanding of how prisma works now as you can see here there's different technologies that we can use for instance right now it supports javascript and typescript in this crash course we are going to be using javascript and the main reason for using javascript is because if you know typescript you know javascript but if you know javascript that doesn't necessarily mean that you know typescript so we're just going to do a javascript just so we have a larger demographic that can actually utilize this video now in terms of databases again mysql or postgres we are going to be using mysql just because i found it a lot easier to download this on your local machine so i'm not going to go over how to download mysql on your local machine but if you want to take a look at that just go to dev.mysql.com downloads and what i would need you to do is to download the community server as well as the workbench and really they're very very easy downloads they're just simply a wizard that you have to follow so go ahead and download that and i'll have some just some links in the description below if you're having trouble downloading i'll have some tutorials down there as well for you to check out so there we go that is pretty much all that we need so let's go ahead and let's read through this documentation and see how we can set up our prisma project so it says here well to create a project the first thing is we have to create a directory so go ahead and create a directory call it whatever it is that you want i already did i called it uh prisma tut that was my directory and then the first thing that you have to do is cd into that directory and initialize a new node project so let's go ahead and do that right now so i opened up my directory in visual studio code that is the code editor of my choosing let me just quickly zoom in a little bit here so i opened up also the integrated terminal that you can of course do that through well this command right over here and now i'm inside the prisma tut directory so now all i have to do is initialize a node project so i can do npm init y and that should generate our package.json file right over here cool so we have just generated that so what is the next step well the next step is to install prisma so let's go ahead and install prisma so there we go let's give that a little bit of time and this right here is going to install the prisma cli so now we can actually use this command to initialize a prisma project so to do that we would do something like npx prisma so this is this is how we access our our cli now if we want to do something specific like initialize a prisma project now what we would do is npx prisma and then init so let's go ahead and let's do that and there we go you can see here that well we have a bunch of different folders and files so you can see here that we have this new prisma directory and in this prisma directory we have this weird prisma dot schema now if you open this up this might all be white for you so you know the syntax highlighting might not be all too great the reason why it's nice for me is because well i'm using uh i'm using a vs code extension known as prisma and this was actually created by prisma so if you want to have that nice syntax highlighting go ahead and install this vs code extension so we get this prisma dot schema file and we'll get to this a little bit later don't don't worry all too much about this so there we go now we have pretty much created our prisma project now the next step is actually to connect it to our database now as you can see here in the prisma. schema we have our database right over here and by default it has postgres now feel free to use postgres if you have that have a postgres instance locally in your machine or you have a postgres database in aws for save go ahead feel free but again we are going to be using mysql now over here we need to also supply it with the database url now the database url is inside of an environment variable so it's going to be inside of this end file and it's going to look a little something like this right over here and actually to get a better understanding of how the structure is going to be we can actually just copy this so copy this url this is going to be a mysql url so we can copy that and you can see here it's going to be mysql and over here it is going to be the username now what is the username well if you have a local instance of of uh mysql running for me it is going to be root so you can see that over here i hope hope that i can't really increase the size in mysql workbench but over here you can see that it is root for me so you can kind of check that out so over here you can say root and then over here well whatever password is in my case my password is simply password and then everything else you can literally leave the same except for the database you can change the database to something else i'm going to change it to prisma now let's go ahead and save this and let's save that and let me go ahead and open this up and i'm going to have to actually write my password which is password and you can see here now i am in in a quick second i am actually in workbench so i actually have if i go to now schema again i apologize if this is a little small i really don't know how to increase the size in workbench but we're not going to be working with workbench at all so i actually have a prisma a predefined prisma table so i'm just going to quickly go ahead and just drop this table so you can do that through a simple command like drop table prisma now you probably are not going to have that so i'm going to drop it and it doesn't seem like it's working for some reason uh drop table prisma why is that giving me an error no database oh sorry i don't wanna drop the table person i wanna drop the database prisma there we go and that should work perfectly fine now what i'm going to do now is actually create the database again so i'm going to create that database because we are defining that specific date database now the reason why i dropped it is because i wanted to show you how to create a database plus i also had some other stuff in there as well so to actually go ahead and see it all you have to do is just right click refresh and you can see a brand new database instance so again apologies if this is way too small uh uh i really don't know how to zoom in here but we're not gonna be working with workbench at all actually so we don't have to worry about that so now now essentially what we can basically do is put that inside of of our environment variable and now we are actually able to connect to our prisma or our sql database so that is really all we have to do for connections so that is it for this section and we'll see you in the next one so now that we have set up our prisma project the next step is to tell prisma how our data is going to look like inside of our database and we do that through schema definitions if we go back to this over here you can see here that we can actually create schema definitions in that schema.prisma file so you can see here in this example we have a post and this kind of represents a table we have profile and then we have users so that is basically what we are going to do now before we are able to do this we need to have an understanding of how the data is going to be organized inside of our database now for this crash course we are going to create a very very extremely simple application this is really an application based on how we can work with prisma i want to build something very sophisticated so essentially over here we're going to have a table that is going to be comprised of the id which is a primary key and the username that is a var chart and this is simply the users table this is just going to be the users table and we're not even going to store a password because i'm not going to be dealing with authentication again because i want to deal with prisma if you want to learn about authentication i do have an authentication crash course that you can actually use in in in conjunction with prisma i'll actually link that in the description so really all we have is an id and the username and this over here is another table and over here this table is related to posts so this table is related to posts so i can go ahead here and just change this to posts and this contains an id this contains a title a post it created as an updated ad field as well as a user id that is an integer and this is going to be a foreign key that links each post to a particular user that way we can actually have a one-to-many relationship and i will show you guys how to do that all in prisma well in the next few coming lectures so let's actually go about doing that right now and for simplicity's sake for actually introducing how we work with schema let's just create this over here so we're just going to create this we're not going to have any sort of relationship we're just going to create the users right over here and i think this is going to really explain to you how we can go ahead and create our schema and kind of migrate that to our database table all right so let's go about doing that right now so remember to do that we have to do that inside of our schema.prisma file so remember that's going to be in our prisma directory and in here we have schema.prisma and this is where we're going to define our schema now the first thing that we want to do is we want to define a brand new table in our database and we do that in prisma through model so we do model and then we define the name of our table now typically a model is going to have a uppercase letter right over here inside of these schema.prisma file so we're going to have model user and then we have basically a bunch of curly brackets and in here we're going to define the columns and their associated types so the first thing that we want to do is we want to provide it with an id so well we say id the next thing that we want to do is we want to provide it with the type and so in this case well this id is going to be an integer so it's going to be a number now you can see here we're getting a bunch of errors and the reason for this is saying hey each model must have at least one unique criteria that only has that has only required fields so essentially it wants us to either mark it as an id or as a unique id and that's basically what is happening here so we have to actually go ahead and use the at id decorator to say that hey this is basically a primary key so now this is an id however what we want to do is we want to auto generate this id we we don't want to provide this id in so what we can do is we can actually default this using the at default decorator so we can default it and we can default it to auto increment so auto increment so essentially now what happens is is well when you add a user it instantiates it as one and then if you add another user it auto increments it to two and that way we have a unique id so with prisma we're going to be dealing with a lot of these decorators and there's a lot of different decorators for instance there's the at unique decorator if we want to ensure that hey something is absolutely unique well we are going to use that specific decorator now this one is going to be an id because i want to specify that this is a primary key so that is the very first thing the next thing that we're going to do is we're going to add well a username and the username is going to be a string so this is going to be the username and behind the scenes what this is going to do is it's going to convert it to a var chart now you know when creating a var chart you could actually specify the number of characters that you want and typically it's 255. with prisma what it does usually is it it it has some weird value it instantiates it at like 190 i don't really like that so we can actually change that by accessing the at db decorator and then we just do dot varchar varchar and then over here we can say well 255. so there we go that is pretty much that so the next thing that i want to do is i want to make sure that the username is unique across this users table so over here i can go ahead and add the at unique at unique decorator and now this basically ensures that hey this is going to be unique and we'll actually look at the sequel that kind of gets created uh kind of behind the scenes in a little bit but this is going to add a unique constraint so there is a bunch of decorators i actually highly recommend you go ahead and kind of just look into them you have the at unique we have the add to map we have add relationship we're going to pretty much look at every single one over here don't worry throughout this crash course but this is really how we perform actions inside of our schema.prisma file this is how we go ahead and define our our tables so let's go ahead and let's do this and that is pretty much that now how do i get this inside of my database so remember my database is right here it is is it is in this local mysql instance for you it could be postgres or mysql or could you even be in the cloud how do i get this new table inside of my database well we do this through migrations and i'll talk about how to perform migrations in the next section now that we have defined our schema inside of our schema.prisma file the next step is to actually migrate that into our database so well we do that with migrations and to to actually migrate our data we are going to use the prisma cli and we're going to use a specific command right over here so we're going to do npx prisma migrate dev uh dash dash name init and essentially what this is going to do is it's going to look at our schema inside of this file and then essentially translate that to our database so you can see here this command does two things it's going to create a new sql migration file for this migration and we will see that in a bit and then it's going to run that sql migration file against the database and so we can actually see what the sql commands that are run inside of our database through this file so let's go ahead and let's copy this right over here and let's just paste this inside of our terminal so let's go ahead and let's just paste that and let's give it a quick second and there we go okay so it seems like it has completely worked you can see here we now have a new migrations directory inside of the prisma directory and if we go here we also have this weird number and this is just a timestamp and we can see here we have a migration.sql if we open this up you can see that the sql that was created so we can see here that we have created a create table and essentially the id is a integer not null auto increment so this is just a primary key and over here we have a username that is going to be a varchar also not null and you can see here that it also created an index for our username because we defined it as unique so it said hey might as well go ahead and create an index and if you don't know anything about indexes don't worry i do have a crash course on that i can also link that in the description you do not really have to worry about that but this is kind of an extra neat feature that it does and over here it also defines that this is a primary key our id is a primary key and then over here we have just a bunch of extra things that we don't have to worry about but this is great this is what it was able to execute based on our very simple instruction right over here so this is all that we have defined and this is all that it has executed and you can see here how much more helpful prisma can be because we don't have to go ahead and create all these complex things rather all we have to do is define this right over here which is a lot simpler all right so let us move on now so now that we have actually migrated it first thing of course that it did was create that migration the next thing that it is going to do is well actually run that migration on our database so let's actually check that out right now so inside of our database again this apologies this might be a little bit small for you but go to your database and go to your prisma directory right over here and if you go to tables if you go to tables what you can do is you can go ahead and right click and then you can just refresh the tables and you can see now you have a users table so you have a users table so if i go ahead and i do something like use prisma so i want to use the prisma database and i execute this all right and now let's do something like select star from users so select star from user i'm going to go ahead and execute this and you can see here that i actually get a table again apologies if this is very small i really don't know how to zoom things in but you can take my word for it that we have a column of id and a user and username that is a varchar so we can see that in there right now which is well this is pretty terrific so we can see here that it actually migrated our data now one thing is that i really don't like capital cases inside of our sql database so one thing to change that we can actually go ahead in our schema and we can change that by saying at at map and essentially here we can say that we want the name and sorry this is going to be an object and we're going to say that we want the name to be well user and apologies is actually it's not going to be an object let's go ahead and let's get rid of that we want the name to be a user now if we want to run this command and actually get it inside of our inside of our database what we can do is we can go ahead and run that same exact migration so we go ahead we run that migration and now we get another another file right over here this is another timestamp and you can see here that it's a little bit simpler so over here we have they dropped the user table and they went ahead and created the user table with basically this over here so with capital case u instead of uppercase u so now if i go back to this over here what i can actually do now is again let's do a quick refresh so i'm going to refresh and you can see here again apologies if everything is small but basically if i change this now to or if i leave this as capital u and i execute this essentially i guess it works still the same in a sequel but in postgres it is more case sensitive but yeah you can you can either you can try to see it or it you take my word for it uh that the the name is now lower cased so that is basically all that we have to do and whenever we make any change that we want actually reflected inside of our database we have to run that migration command so that is pretty much that so far we have learned how to migrate data from our prisma schema in to our database and it kind of looks a little something like this so we have all of our definitions over here and then through the prismacli we run that migrate command and it migrates all that information in to our sql database but that pretty much assumes that our prisma schema is the only source of truth and that our sql database is kind of out of date now what happens if we run into a different scenario where actually our mysql database is more in date than the prisma schema for instance what if we have created an additional table in our database that we haven't defined in our schema now one thing that we could possibly do is just go ahead and manually add that in our prisma schema but a better option is to use something known as introspection and essentially what introspection does is it allows prisma to go into the database read all of the tables read all the columns and then see how that relates to the schema that already exists now if there are any changes it goes ahead and it changes them let's actually take a look at how it does that so i'm going to go to workbench and i'm just going to quickly create this test table that we will eventually drop so i'm going to quickly create it and there we go so now we have a test table so if i go ahead and refresh this again you might have to take my word for it but it created a test table so now what we can do is instead of going into our prisma that schema and creating a new model we can actually use the prisma cli to interpret our table our database uh tables and actually create the appropriate schema and to do that we would use something known again as introspection and this right here is the command that we will run npx prisma introspect dash dash force so let us go ahead and let's run this command and you can get this from this over here prisma dot io docs concepts components introspection or you can just go ahead and just search prisma introspection to to get the the folder or the or the web page so let's go ahead and let's paste that in there and okay and there we go okay there seems to have been a change and there we go you can see that our thing got completely changed so over here we have an id which basically an id int and over here with the decorator that is an id and that basically translates to the primary key that we created and over here i created an active an active column that is a boolean and i also said that this was nullable because remember in sql we specify things that are nullable that are not nullable through the not null constraint and you can see here that it has actually created active and it said that this is a boolean but this is optional and this is how we define things whether they're nullable or not we have this question mark over here so that is pretty much that which is terrific now i don't want this table so now what i can actually do is either delete it in our actual database and in our schema or i can just simply delete this in our schema and just run the migrate command so we can go ahead and run this command and give it a quick second so it's going to say here hey there's something wrong here there's nothing wrong it says hey are you sure you want to do this we're probably going to be end up deleting a table with some data i'm going to say it's fine there's no data in the anyways and you can see here we get a new migration and you can see that this migration let's quickly go over here this migration has not dropped it oh and the reason why it hasn't dropped anything is because i didn't save it apologies let's go ahead and let's just create let's do this migration again okay so now we get another migration and you can see here that all it did is just dropped that table so that is how we pretty much relate to data or how we can move data from our database uh to prisma and then from prisma to our database so that is all we really have to worry about in the next section we're going to create the post model and then we are going to essentially uh define how we can relate data together through our schema all right so we have created our users table let's go ahead and create our posts table now remember how our data is going to look like so we have completely created this but now we have to create this table and we also have to find some way to relate many posts to a particular user because over here we're going to have a one too many relationship so let's actually go about doing that right about now so let's go to our schema and of course what we are going to do is we are going to have a model so we're going to have a model now of uh this because of of the introspection it changed it to a lowercase user but essentially i can i like having the models be capital case but i also do like uh inside of our database for the table names to be lowercase so we can just simply use the at map so over here now what we can do is we can essentially create our post and over here we can similarly have the at map and basically say that hey the name of this table is just lowercase post all right so what is the next step well the next step is going to be very similar to what we have over here so the first thing that we have to do is we have to define our id this is going to be an integer and we're going to have a few decorators in here so the first decorator is going to be the act id decorator to define that hey this is going to be a primary key and then we're going to have an at default and then we're going to have an increment so there we go that is the absolute first thing the next thing we need is the title and then the post so we can go ahead and do that right now we can say that the title is going to be a string and then we can also say that the post is similarly also going to be a string we also probably want to increase the limit of this so essentially what we can do here is we can do at db so we can say at db and then we can say dot var char and essentially maybe we can say that a post can only be let's say 500 characters so we can do that and now the next thing we need to do is we need to have these two fields the created that field and the updated ad field so let's do that right now so we have the created act field and this is going to be of type date time so this is of type date time now if you never know the type of a certain thing you can probably guess it most of the time especially if you have been working with types or you can just go ahead and just search it up on the prisma.io page so there we go so we also want to default that to when this post was created so we can actually have the at default decorator and then we can basically say now so this is basically whenever this is created i want to run this function right over here okay so let's also do the updated act this is also going to be date time and then we are going to have a special uh a special uh decorator for this it's going to be called update at that so whenever this post is updated at essentially it just changes the date time accordingly now the absolute last thing that we need to do is add this user id over here and relate it to this user so how do we do that well you might think okay that is relatively simple you would just have a user id and we can say that this is an integer now we also have to somehow define that this is going to be a foreign key a foreign key that basically relates to this model right over here now to do that we're going to create a separate column known as user and we're going to define that as the type user so this particular model over here so we're going to say that hey this is going to relate to one user and then we're going to use the at relation decorator and then this is going to take in two parameters so the first parameter is the fields and this is basically the fields within the model that we are creating so essentially over here this is the fields within the model that we're creating essentially we're going to pick a column that we're going to use to relate to this uh table right over here so we're going to use our user id column so over here we can say user id and then what we are going to do is we're going to have another parameter and we're going to say that hey this references so this references and another array this is going to reference a specific column in the type that we have defined defined over here so whatever model that we have defined over here we're going to pick a particular column now in this case we're going to pick the id and then over here we can basically just say id and then at that point we are pretty much done that is pretty much it now the only problem is we also have to do the same thing over here so over here what we have to do is we have to say that hey we have posts and that relates to well this model over here which is going to be the posts and of course we don't have a colon and it's actually going to be an array because we have a one-to-many relationship so that is pretty much all that we have to do for some reason i am getting some sort of syntax errors let me see here let me quickly highlight over this so we have references is oh sorry this should be references not reference so there we go that is pretty much all that we have to do let me quickly just zoom out of this so you have kind of an idea of everything that we have here so basically what we are doing here is we are defining user and that we're saying that hey this is always going to be just one user and over here we're defining the relationship and essentially we're saying here the fields is going to be the columns within the post and then we're going to say that hey we want to relate our user id we want to refer that to the id inside of the user column now over here we can basically say that hey we have multiple posts that are essentially of this particular type and we can't even have many of them so that way we have a one-to-many relationship and a many to one relationship so that is pretty much all we really have to do uh if you don't really understand this this is kind of basic sequel uh so if you're if if the sequel part of this is a little bit confusing uh i will in the future have a sequel crash course and i can probably link that in the description as well but this is just basic a basic way of creating foreign keys inside of a prisma schema and let's actually take a look at that by migrating it so let's go ahead migrate this and uh we should see a new migration and we should be able to see our table so over here you can see here we created our post table and we see here we have an id we have a title we have a post and then we have this right here this is the user id and it is an integer not null and of course this is a primary key but over here you can see we have the foreign key constraint right over here so this is actually a foreign key that references the id in the user table and also adds some other things on delete cascade on update cascade which is actually really ideal we probably want that anyways so that is pretty much that so we have actually learned how to relate data together inside of a prisma schema so now let's actually go ahead and use this schema to fetch our data manipulate our data delete our data and things of that nature and we're gonna do that in the next section so far the only way to actually see our database is to open up workbench and see it in our actual database instance but prisma actually has this really cool gui that allows us to much better visualize our data this is known as prisma studio so to open this up what we can actually do is go to our terminal i'm going to open up a new terminal and what we can do is using the prisma cli we can do npx prisma and then studio and then we can go ahead and execute this and now it is running on localhost five five five five and you can see here here are our models so we have our user model we have our post model and these are all the models that we have defined right over here now if we go ahead and we click on it you can see here all of our columns now right now there actually isn't any records inside of our database which makes complete sense but we can actually go ahead and actually add records if we wanted to so you can see here that this is auto-incremented but we can also say that hey we have a username of well lathe harp for instance and we can go ahead and save these changes and let's quickly refresh so we can actually see those changes or sorry this is null for some reason let's go ahead and let's change that and let's add that particular record okay i'm not really sure what's going on here let's quickly uh delete this record and there we go now we have this record over here so we can actually see that we can save that change and then we can go here and we can also see all of our posts as well so this is a really cool way for us to actually visualize and see our data so if you want to do that we will continuously use this gui in the in the future sections but if you actually want to be able to visualize and see it then go ahead and run it on local five five five five so the last thing that we actually have to do is to create our rest api and use prisma as the orm now to do that we are going to use prisma client and if you go back to the docs to start from scratch docs the last thing that we really have to do is install this prisma client and essentially once we install this prisma client it is going to create a bunch of directories inside of the node modules which makes sense and also once we install it it's going to run this command prisma generate now essentially this is going to cause the prisma cli to read and interpret our schema in line three and four and then it is going to go ahead and update our prisma client inside of our node modules so as soon as we install it is going to run the prisma generate command however once we install it and then we make any sort of subsequent changes we have to cr we have to run the prisma generate to go through this workflow over here so for it to read our schema and make any sort of updates in the node modules so let's go about doing that right now so let us install that and i'm going to install that in the first directory so we're going to go ahead and install the prisma client so we're going to install the prismaclient there we go and now we want to go ahead and create our api so let's go ahead and let's create an index.js file in the root directory in the root directory this is going to be an index.js file now this basically sold caps so this over here can be any api that we have created if we go back to the docs you can go over here we can basically see the different types of apis or node frameworks that essentially it supports so you can see here that it supports express it also supports apollo it also supports graphql supports nest for our example we are going to use express so we're going to use express uh if you don't have any knowledge of express that is okay it is just a simple way of creating a rest api and i do expect you to have knowledge of a rest api if you are taking this crash course so we're going to use express so to do that well really all we have to do is just install express and let's give that a quick second and over here once this installs we are going to inside of our index.js create our express project so let's go ahead and let's just do const express and we're going to require in require that in from express and then what we're going to do we're going to instantiate an express instance and this is going to be called app and then we are going to simply do an app.listen and we are going to listen on port 5000 and we are going to console.log listening on port 5000 so very very simple now just to quickly test it out let's create a get route that just goes to the root directory and let's do a rec res and essentially let's go ahead and basically send back i am working so let us go ahead and inside of here what we can now do is node index dot now i'm not going to do node and the reason for that is if i make any change i have to go ahead and restart the server every single time and that can get really really annoying so instead what i'm going to do is i'm going to use something known as nodemon index.js and essentially what this does is it catches any changes and it updates the server automatically without me having to shut it off and run it run it back now if you don't have nodemon installed what you could do is just do something like npm install nodemon and with the g flag so you can install it globally on your machine now if you are on mac and linux you will probably have to have the sudo right over here so that essentially you can do it in administrative mode and supply your password now i already have it installed so i'm going to go ahead and use nodemon now you could use node but beware that whenever you make a change you have to restart your server so i'm going to use nodemon and go ahead and run this and you can see here listening on poor five thousands now now if i change this to an explanation mark you can see here that it automatically changes it whereas with node i would have to restart it so let's just quickly test this out let's go to localhost localhost 5000 and you can see here that it is working okay cool so for this particular application we are going to use postman so let's go ahead and let's open up postman see where i have that in there you can see my messy desktop apologies for that let's open up postman let's just wait a little bit i'm not sure why this is taking so long anyways i'll open up postman a little bit later but we're going to basically use postman to test our routes so let's go ahead and let's actually start creating our routes in the next section let's actually start using the prisma client inside of our routes that we are going to create so the first thing that we're going to do is we're going to create two routes for the user we're going to create a route where we can get all of the users and their associated posts and then we're also going to create a route that allows us to well create a user and we're going to do this through the prisma client so let's go ahead and do that right now so inside of this directory let's actually create a new folder called routes so this is going to be called routes and in here we're going to house all of the routes associated to our application now in here i'm going to have a a user.js file and this is going to contain all of the routes that are associated to users so we're going to have our get all users route in here and then we're also going to have our create user route in here as well so to do this this is just simple express so we're going to do const router and we're going to get that from express so we're going to require in express and then dot router so this essentially is is what we are going to use to create our routes so now what we can do is we can actually go ahead and create get requests or post requests uh post requests or delete requests now the one thing that we actually have to do is at the very bottom we actually have to export this because we need to get this router inside of our index.js file because this is ultimately what we're running so we want to basically import all our logic into here so now what we can do is we can do modules.export and we can export our router and to essentially get it inside of our index.js file all we now have to do is use it as a middleware so we can essentially now do app.u and we can define a predefined path as the first parameter so any uh any um any path that is slash api slash user that starts with this i want you to direct it to well we're going to require in the router from the users so the routes from the users so that is essentially what we are going to do one last thing that we have to do is to be able to access data from the rec.body we have to use app.use express json so this is just basic express setup if you don't really know express this is okay all you have to understand is how a rest api is done this is just a little bit of setup so in here now we can actually create our our endpoints so let's create our first endpoint to get all of our users now remember if we go to our gui at this point we have one user inside of our database so we should actually get this user right over here and this user right now has zero posts associated with them but we should still get an empty array of posts so let us go ahead and let's do router dot get and this is going to be just the slash and then we're going to have here the wreck res so rec res and now what we want to do is we want to access all of the users inside of our database now how do we do that well we do that through the prisma client so now what we can do is we can use that client that we actually installed so we can go ahead and require that in so this is at prismaclient and we can essentially get the prisma client from that and then what we can do is for each model that we have created the client is going to create a particular object that we're able to use to interact with our database so now to actually access those what we can do is we can basically say new client we can instantiate this client and we can say that hey i want the user object now there's also going to be a post object right over here now there's not going to be anything else but if we create models essentially what happens is once we run our generate command this actually gets manipulated inside of the node modules right over here so now we can actually get the users we can also get the posts if we have comments you would be able to get comments but we don't have them at the moment so we can basically say user and now what we can basically do is we can get all of our users so we can say something like let or const users is equal to user dot find so you can see here find the first iteration find many or find a unique this is kind of like find one or find by id we are we're going to want to find many of them so we're going to go ahead and find many of them and essentially what we want to ultimately do is find them all so essentially what we can basically say is hey we want you to find them all no conditions however let's say we don't want certain parameters so let's say we only want uh uh we don't want you to give us back the id let's say we only want the username and the post so remember here we have id username and posts so to do that in typical sql we would do something like select username from this table rather than select star from table well we can essentially add a selector right in here we can basically say that hey we want to select and then we pick what we want to select so over here we can say that hey we want to select the username you can see here how cool this is it kind of auto fills for us and we can say true and then we can say that hey we also want to select all of the posts and we can say true for that now if we also wanted to filter so if we also wanted to filter what we could possibly do is have a where so we can have a where and we can basically say hey where the maybe the username is you know this or whatever or maybe if we had an active active column we can say where the uh the active is is false or maybe you would probably want a query for where the active is true so we could possibly do that as well so that is how we are going to filter we'll talk about filtering a little bit later it is fine but for now we'll just have the select now this is going to be asynchronous because we are communicating with our database so to kind of fix this issue we have to just mark this as an a sync function and also mark this as a weight so that is pretty much all we really need to do now we have gotten all of our users so now essentially we can do is a res.json and we can go ahead and just return all of those users so if we go to postman now i have a prisma directory and now what i can do is i'm going to go ahead and just create a request i'm going to call this request get users all right so i'm going to call this request get users and i'm going to just quickly go to localhost five not three thousand five thousand i'm just gonna copy and paste this url so i'm gonna copy and paste this url over here so now if we go to uh localhost 5000 slash api slash users and then slash and make sure that this is a get route we should get all of our users so you get slash api slash users let me go ahead and send this off well this doesn't work for some reason uh let's see am i missing something here okay because i have user so let's go ahead and change this up again and there we go let me quickly zoom in a little bit you can see here that we get our data back which is terrific now let's say i only wanted um let's say i didn't want the posts just to kind of quickly illustrate this if i don't want the post i just wouldn't have this in there so now if i were to make this request again you can see here i can actually specifically select for the people that i want we can also let's also have a where clause in here let's add a where clause and this where clause is going to be let's say where the username for some reason i'm not filtering by id for some reason where the username is this now if i were to execute this you can see that hey none of this meet this condition so we don't actually get something in our array now over here it doesn't really make sense to have a where clause and if we wanted to filter by a specific username might as well use the find unique which we will see a little bit later in the in future routes so that is well the get route let's actually go ahead and create a user now so let's do router so right here right below we're going to do router and we're going to call this router.post and we're going to have the same path because well this is a different verb that we're using here so we're going to do rec res and as you can imagine we're going to have a lot of asynchronicity for this we're going to mark this as async and now what we're going to do is essentially the user if you want to create an account for this extremely simple application all you have to do is provide us with a username not even a password you just have to provide us with a username again i don't want to dwell on authentication and all that stuff i really just wanted to teach you how we can use prisma so this isn't a real application i highly wouldn't recommend doing this again if you want to actually create proper routes i do have a great crash course about jwt authentication that i will link in the description but for now all you have to do is just provide us with a with a username that is unique so you can't provide us with the same username for instance you can't go ahead and provide us with let me quickly save this you can't go ahead and provide us with lathe harb because that is already in use so to access our uh our username we're gonna say that hey this is going to be in the request body so to access that you would just do something like const username we're going to destructure out username from the rec body and then the first thing that we're going to want to do is basically check if this user already exists now how do we check if this user exists well we can use the find unique command right over here so we use find many but we can also use find unique so we can say const user exists and we can basically say await dot user and then we can say dot find unique so we can find unique and then over here we can have a where clause so essentially we can say where where well where well the username the username is the username that we provided over here so it would look ultimately something like this so where the username is the username that we provided over here now because the key and the value are this exactly the same in javascript you can just simplify that down to this and then let's say that we only want to select four so we only want to select for the the username itself so we don't really care for anything else we just want to select for the username so we say select true okay so now that we got that essentially let's just do a quick res dot json and let's just return back user exists that's all we want to do just so we can see how this looks like so inside of postman we can go ahead and we can create another route and we're going to call this create user we're going to copy this over here because it's going to be exact same path just a different verb and let me quickly save this and save this as well now in the rec.body in the rec.body i am going to provide it with what is going on here i'm going to provide it with raw and then json and i'm going to provide it with a username so i'm going to provide it with username i'm going to provide it with a username that does already exist so i'm going to provide it with the latheharb username so latheharp so let's go ahead and let's send this off and you can see here i get back an object of well username lathe harp basically symbolizing that hey this does exist now if this doesn't exist add an extra b in there you get back null so now what we can basically do is essentially we can check hey if this user exists so you can say basically if user exists so if basically this is not null what we can essentially do is return back res dot status we can essentially throw an error you can return back a status of 400 and then we can provide you know some sort of message we can say hey message that the user is already user already exists so the user already exists so essentially now we wouldn't do any of the other logic that we have before or we have after this command right over here if our user exists now if our user doesn't exist essentially now what we can do is we can go ahead and create that user so we can do something like const new user and essentially we can say await user and now we're going to use a new verb or a new method known as create and you can see here that there's so many different methods that you can use we have count we have create we have create many there's so many we're not going to get into all of them unfortunately but you can probably figure them out through docs i'm just going to kind of explain to you how uh most of them are done essentially here uh like count allows us to count all of the records and we can provide certain filters as well in here create we're gonna use uh right now create many works very similarly instead but we provide it with an array we also can figure out how to delete we're going to delete through a certain query i'll show you guys how to delete update find and create and maybe i'll also show you how to do some of the other things but but yeah i'm probably not going to cover every single one in this crash course but i'll try to do my best so let's go ahead and let's just use the create now so we're going to do the create and now let's say we want to create so we provide it with an object and then over here we create it with data so we have the data and over here we specify the data that we want to include in here now right here if you remember if you go back to our studio really all the data that we need to provide is the username so we can essentially say that hey we want to provide the username of well the username that was provided in the erectile body we can just simplify that down to simply username and now the absolute last thing that we can do is we can go ahead and just res.json the new user so we can go ahead and save that and let's go ahead and let's actually create this right over here uh let's paste that in there i'm just not sure why that's uh oh sorry i'm there we go so let's go new user so now what we can do is we can go ahead and let's create this new user let's actually just change the name to something else so change the name to uh lebron so this is going to be a new user we're going to create that user you can see here that it has created the id and it has also created the username if for some reason we also don't want that we can also use the select and specifically select for what we want so we can either select for the id or for the uh or for the username or for both now uh if we leave it default if you don't have that select option it just selects for everything so now that actually has been created inside of our database and we can actually see that through the gui so if i refresh the gui you can see here that we have two records and to further prove that to you if i open up workbench so if i open up workbench which is our actual database and i did something like select star from from users or from user and i execute this you can see here again very very small i apologize but there's two records and lebron is actually one of the records so that is well pretty much it and uh next section let's actually go on and let's create our post routes which will be a little bit more complicated but they're going to be more involved and going to introduce a lot of the methods associated with the prisma client so let's do that next okay so let's go ahead and finish off our project by creating the post routes now before we do that i think you guys might be a little bit confused as to how i got these methods over here now really how i got these methods was i used the prismaclient i appended the dot and i kind of figured out hey all of the methods that are associated with this object right over here so let's say you wanted to delete something you would go ahead and just do user dot and then well you would look at it and you say okay well delete or delete mini now let's say you select delete many but then you have really no idea what goes inside of this parameter one thing that you can do is just hover over it and this could give you the type definition so you can see here the arguments is select include and where now if that still doesn't make much sense to you what you could do is just go to the documentation and i highly suggest this because i will not be able to cover all of the different methods in this crash course because i don't want this to be too too long so just go to the documentation and you can see here this has all of the commands that we are going to be performing all of the crud commands so for instance if you want to create something over here you can see to create a single record you can see well we already did this but you can actually see how the data looks like if you want to create multiple records well this is how it's going to look like instead of passing in an object you pass in an array of objects and if you want to create a record and i don't know what this is but yeah so this is how you do and perform all of these different things so this is reading right here if you want to go ahead and update so if you want to update a single record well you would use user.update and then you would provide a filter and then this is how you would go ahead and update it if you want to you know update multiple records update or create a record so this is probably upsert over here so you just read the documentation if you really want to kind of fine-tune what you want to use i again i won't be covering everything i just want to be able for you to actually be comfortable with prisma and just use it so that you can actually read the documentation and use whatever it is that you want so the last thing that we're going to do is we are going to go ahead and we're going to create our post routes so let us get rid of that so we're done with the user's route let's get rid of all of these so over here in our route let's just create posts we're going to call this post just to be consistent and we're going to have the same kind of foiler plate so over here we're just going to import all of this and we're going to export our router so let's go ahead and export our router and then in here what we are going to do is we are going to create our first route and now let this route let our first route be a post request to actually create a post so we're going to do route dot post and then this is going to be well the root directory inside of the directory that we specified and then we're going to have rec res as you can imagine this is going to be asynchronous so might as well have the async keyword so the absolute last thing we have to do is inside of our index.js we have to let uh we have to let our express server know about this so we would just say api and we change this to slash post and we will just change the route to or the path to post okay cool so now we can go ahead and actually create our post now to create our post what we have to do is we have to create a post and associate it to a particular person so remember a post cannot be created without a person so because a post has a a many to one relationship with an individual so in the rec.body so in the rec.body not only do you have to provide us with let's go to studio right now not only do you have to provide us with the title and the post but you also have to provide us with the user id like for some reason oh here we go now i can scroll so you also have to provide us with the user id they created that and they updated that we don't have to worry about that because it is going to be auto generated the id also will be auto-generated and the user is going to be essentially created based on the user id that we have over here so we have two users now let's say lebron made a post and so we're going to basically pass in the id of two okay let's do that right now so essentially we need the title of the post we also need the content and we also need the user id all right so that is we're getting that from the request body that the front end is responsible for adding that in the request body and now what we want to do is we want to first check if the user even exists so we want to check if hey this user id is actually associated to a real user because we don't want to add a basically we don't want to add a user id that is actually not associated with the user we and it actually won't be possible because we have our foreign key constraint so let's actually just check that over here so how do we check that well we can just say something very similar const user exists we kind of did this already so we can say const user exists and we can say user dot find unique and then we can say well we are going to find unique by the id and we're going to pass in the user id so that is essentially what we are going to do now remember if this user does not exist it is going to return null so we are going to say hey if this user does not exist if this user does not exist what we are going to do is we are going to return res dot status of 400 we're going to provide a message of we're going to provide a message of user not found user not found that is what we are going to do so that's just a quick little check now if the user actually ends up existing now what we can do is we can actually create a post so we can say const new post and that is going to be a wait and now what we want to do is we want to use the prismaclient but this time we want to extract the post from it so now what we can say is a wait post and now we can basically say create now remember we can have multiple things create create many uh remember if you want to use create many for instance go ahead and read the docs essentially it's the same as create but instead of passing in an object we pass in an array of objects so over here we would do create and let's just you know go through the docs one more time just to kind of explain to you how i would typically do this i want to create a single record so it's going to be dot create and i'm going to pass in the data through this data object so let's do that right now so data and then over here we're going to provide the title the content as well as the user id so we're going to provide the title the content and the user id all right so that is creating it and let's actually go ahead and send that back so let's do json res.json and we're going to return that back all right so let's go ahead and save this really quick and let's go to over here let's create a brand new request let's copy this and we're going to save this we're going to save that we're going to change this to create post we're going to make this a post request and now what we can do here is inside of our body we can add our content and one thing that you could possibly do is more validation so right now we're only validating our user if they exist but we're not even validating if the title exists or if the content exists or if the title is of a certain length so that's like increased validation that you can probably do later on in the future so yeah so you can probably do that with like express validator or something but you know for the for this crash course who cares so uh let's uh let's provide a title and this is going to be a title of uh this crash course sucks the content is this uh this instructor is so bad please dislike and don't sub so this is a this is a hater and then the user id the user id is going to be 2. remember the user id is going to be a user inside of our actual table so lebron is saying this to me for some reason ok so we can go ahead and we can execute this and it is failing let's wonder what the error is let's see here so i had a few errors most of them were just syntactical errors but in case you were following along essentially the first thing was over here i didn't provide the where condition so essentially i went ahead and i just did this over here and my condition was inside of this main object that's not allowed in prisma that's not the correct syntax we actually have to provide a where object and in here we provide our condition the reason for this is because we could have multiple things like select as well in there so that is the first problem the other problem is over here i assumed that the column name was content by accident but it's actually post so over here instead of doing a direct mapping it's it's just mapping posts to content and the last little error that i had was uh this was actually slash users and not slash posts so or sorry it was slash users and that slash post so i went ahead and i changed it to slash post so now if i go ahead and i actually create this you can go ahead you can see that our data has been created if you go to studio which is a reflection of our database you can refresh this and you can see that this has been created and what's great about it is now if i go to users and i uh well it is refreshing give it some time to refresh you can see here that lebron actually has one post and you can see what that post is and now if i actually go back to the get users route where we have an array of objects as the posts over here if i send off this request again i can see all of lebron's posts all right so that is terrific let's work on one more route and this route is simply going to be well just fetching all of the posts associated to a user so let's say you go to a user's account and you want to fetch all the posts let's go do that right now so let's say this is going to be a router.get because we want to get all of the posts and everything so far we have been doing in the erectile body but let's say for now the user id is supplied in the params just just for uh just to change things up a little bit so we have wreck res and then what we are going to do is we in here are going to fetch all of the all of the posts associated to a particular user now to do this it is very simple you can just do something like const posts and we can await and then we can say post dot find many so over here we're going to find many and so we're gonna do find many and then in here we are going to basically supply it with well everything that we need so we're going to say the where clause so where the where clause is the user id is equal to the user id that we have supplied now to be able to access that well we can do that very similarly like we did with the rect.body but instead this is going to be rec dot params and we're going to access the user id now one thing that you have to keep in mind is that this is going to be the string it's not going to be an actual integer so we actually have to parse in this right over here so we don't get any sort of error now the next thing we can possibly do is is select for what we want so let's say i am going to select for well the title uh we're going to mark that as true let's say the created ad if you want everything you don't have to include this uh this uh select for now so let's say you want the title let's say you want the uh the the the post as well of course uh so that will be true let's say you also want the user you want all the information associated to the user so you can say true to that so now what we can do is very very simply just go ahead and return all of the posts and now let's go ahead and test that out in postman so let's create a brand new request and we're going to call this get posts by user so let's go here and in the param we're going to provide the id so we're going to do two for lebron and now if i go ahead and i send this off i get
Info
Channel: Laith Harb
Views: 12,142
Rating: 4.9691515 out of 5
Keywords:
Id: mU8-nKwfw4Y
Channel Id: undefined
Length: 77min 36sec (4656 seconds)
Published: Mon Apr 26 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.