6. GraphQL and TypeScript: Using an ORM - Prisma 2

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome back in this video we're going to look at using prisma 2 as our orm in the last video we used sqlize and we found there was a little bit of trouble setting it up with typescript and you know there was just basically a lot of boilerplate code with prisma 2 things are much simpler and i think prisma 2 is pretty much brand new in the sense that it was in beta for a while but i think now it's in regular release but i'm pretty sure you're going to find it to be a powerful tool and after this video we won't be going back to sqlize we'll probably be using prisma for the rest of the project so if you go to their home page you can see that prisma is described self-described as a next generation orm for node.js and typescript which means it's set up to be used with typescript it's a typescript based orm so we're not going to have the trouble that we had with sqlize and getting things set up all right and if you take a look at their docs they have two different ways you can get set up right you can add prisma to an existing project so let's try to do that first and then we'll come back and do it from scratch all right so first to set up prismo we're just going to need to install it so let's do that you can just copy this right once you install that that includes the prisma cli and if we run some different commands with the prismacli we can jumpstart our project for example we can do npx prisma init and that'll give us a migrations folder and it'll give us a prisma schema which is something we're going to need so let's go ahead and copy this all right so you can see that we've got this prisma folder here and i said that we were going to get a migrations folder but we won't get we won't get that until we actually run a migration but we do have this prisma schema right the file itself is in a folder called prisma and the file's name is schema.prisma and again we're using postgres so things are already configured for that usage all right we'll just need to add the schema also you can see that a dot env file was added to the project all right and it shows you how to add in your your connection string variable values for your postgres database right so you can just add in here your username your password and then the name of the database so i'm going to pause the video and enter in my values and you should do the same if you're following along okay so if you've got your connection string all set up let's go back over to the documentation actually we were already there sorry about that so you can see down here after they show you how to set up your connection string they tell you that you can do introspection so if you have an existing database you already have some tables in there then you can just use the introspection command to grab the information from your database and have a schema a prisma schema created for you and all you need to do is run this command here npx prisma introspect so copy that let's run it and boom there's a schema all right now this schema has our project model our project assignment model and our user model all right things are set up just a little bit differently here though all right so let's go through it piece by piece recall before right we had our project it had an id which was an auto incrementing integer and that was the primary key all right so it's prisma this ad id means primary key all right we had a title which was a string and that is varchar 255 and you can get that just by adding d at db so for example if i just type in at here i can get a lot of options i choose db i hit dot and i get varchar right and i can add in 255 so the auto completion feature in prisma is amazing also if you remember our status was a string it was also a 255 character varchar string created that and updated that were both uh part of our our models although they were automatically included with uh sqlize as to where with prisma we need to explicitly include them in our schema all right now updated at if you do the at mark thing and you get default well we don't want to use default if you type in say you it brings up updated at so that gives you that type definition right there now before we said with our project we had an array of users right in this case the way we're going to set up our prisma schema to get our many-to-many relationship set up we're going to declare an array of users this time we're going to call them members as in project members that's just a custom name right but instead of using an array of projects we're going to use an array of project assignments right that's going to seem weird but that's how we're going to relate our projects to our users all right so let's go down to the user model all right again we have our id which was actually a uuid of type string it was our primary key that's what the ad id means name string email which was unique and a string so remember with sqlize we said unique is true and that made postgres set up our table in such a way that if somebody tried to add another user with the same email as an existing account an existing account then it wouldn't work and that's what this unique here does for us it just makes postgres set up the database that way alright our password was a string again db.barchar created at default now updated out we can do that again updated that now our user has a list of projects all right so lowercase p projects and that won't be a list of projects themselves there'd be a list of project assignments okay so that takes care of our familiar project and user models right and then with project assignment created at updated at and our project id before we had it with a a large p this time our database was set up a little bit differently so it's giving us a lowercase p so don't try to use your i think if you did introspection on your database with the database you created when we did sqlize you should have an uppercase p here but i've added some different tables to my database in the interim so that's why things look a little bit different you can keep them uppercase if you like but prisma tends to make everything lowercase here so i'm going to do the same user id as well is going to get the lowercase here and we have to make sure that it knows where you making that a uuid here and then for our foreign keys right we've got a relationship between a project um our project id here and the id in the project model and that's how this that's what this reference is right here this is our foreign key setup i'm just going to change this a little bit and make this a lowercase p project and i'm going to do the same for user just to be consistent all right and then once we run our migration we're also going to automatically install our prismaclient and our prismaclient is what we're going to use to run our queries right with sqlize we use sqlize for example model dot find all that allowed us to find all of the um records in a table of a certain model in this case we're going to use prisma to do that so not sqlize dot model.findall but prisma dot model dot and it's actually going to be find many all right so looks like we've got our schema set up in the correct way we didn't have to do much to it because with introspection you automatically you get this automatically generated schema that matches your database perfectly right but it's always good to go over it make sure things look the way you want them to look before you do a migration and don't forget here this was our composite primary key for the project assignment relation table right so again we're using project id and user id so if you've made if you've camel cased it up here make sure you've done that down here as well and over here and here as well okay so we should be good to go let's go ahead and do a migration so if you go back to the documentation actually and the only reason we're doing a migration here is because we've changed the schema a little bit so let's move out back not to adding an existing project but to start from scratch and that gives you the migration command here and since it's going to be our first migration we'll be okay with the name init it's the initial migration so let's run this it's probably going to give us a warning about losing data you see that right here all data will be lost right we're just going to drop it everything and then recreate the tables it's okay that we lose all the data remember i have the um those gists at my github so we can just go ahead and create a seeder file and add that back so go ahead and hit yes all right so now our database is synced up with our schema and all right we've generated our prismaclient and our prismaclient is in sync with our schema so that we can call the models as we see them defined here alright so let's just go check our database real quick all right so if i refresh i still have the tables but now for example in the user table all of the data is gone right likewise for project and project assignments also note that with sqlize if we created a model with a singular name like project it pluralized it to be projects but prisma doesn't do that so be aware of that also we have this migrations table and that keeps track of our migrations and that's going to be useful in production all right good so let's go ahead and seed our database so we can get our data back so if you recall at my github i have that just it's called ts-gql-5-data.ts so if you open that up get the raw code and copy it all right we can create and by the way you don't need this database folder anymore and because we're not hooking up to sqlize anymore so just go ahead and get rid of that add a file to the root sorry not a file but a folder called just called data why not and then in that folder create a file and we'll call it seed.ts and then just paste everything from the gist in there all right good so the first thing we'll want to do is we'll want to add our users so before we were using our utilities um file to do that's where we added a lot of our logic in all right so go ahead and comment all this out or delete it if you want we're not going to use it again i just somehow i'm holding on to it for sentimental reasons i guess all right good so first thing we'll need to do is um what shall we do all right we'll import our users okay and if you go back to the documentation they give you this little skeleton for running your queries right you and using the prismaclient so it's right here so just copy that all right and add it that i did not want to do i don't know why i did that okay all right so we brought in our prismaclient we can use that now and we'll write our query right here okay so again we're not using sqlize but we can still use basically the same structure it's just rather than using db.model dot the query is we use prisma dot model which in this case is user autocomplete is doing us a treat and then we're going to do create many all right even though we only have two records it's still more than one all right and inside here open up a set of curly braces and for us we'll need to add a field in prisma i mean you need to add a field called data all right and then we can add our users array okay and that will add all of our users from the list and then we can make sure that we're getting those users by querying the database immediately afterward and it's not find all but find many and we can just grab the data as it is alright so this file is utils.ts it's in the source folder so we can run it all right that should be okay good and here's our data right here all right so you can see that we are not getting any information about projects we're just getting the basic user data here okay but we'll get there this just shows us that we've got our data in the database we've got these new records added so let's go take a look all right users view edit data all rows and here we go we've got our three users back okay so let's add the projects all right so remember we're just exporting an array called project so in our utils.ts file you can bring those in all right and just change our create many function to use the project model typed in just p in the autocomplete brought it right up for me again prisma is really good with that and i can hope i hope you can appreciate how fast we're up and running with prisma and how quickly we're able to start making queries against our database all right so in this case it wouldn't be all users but all projects make sure our model is correct okay so let's run that command again all right it looks like we were able to add those projects as well and we're not going to go back into the database and see we should trust that they were added correctly we'll actually need to go back to the database because as you remember in our seed for adding assignments we needed to add the existing users id which is a uuid so go back to the database and say for our first user who is octavio we'll grab his uuid copy all right we'll add octavio or we'll assign him project number one and also project number two but we also want to add farah to project number one so let's go back all right good so it should be good to go there let's add these assignments right now if you remember the name of the model and we can go back and look at our schema again was project assignment right so if we go to or if we try to add in our model name here we add in p we see project assignment comes up and it's lower cased here all right is that okay let's go back to our schema just to make sure all right well for some reason prisma likes to camel case these model names right so it should be okay though so let's use that all right and then for our data will be assignments all right but now we're getting an error so it says that basically our data type is not matching up with what our schema has okay so you see here it says that type project id number user id string is missing the following properties from type project assignment create mini input and it has lower case values here so remember we changed things in our schema but we didn't change them in our our seed value so here we should make these camel cased makes you wonder why i even bothered doing this in the first place but i just wanted to be consistent since prisma uses a camelcase naming convention all right so it looks like our error went away we should be good to add these assignments so let's go ahead and do that looks like the assignments are added good all right so prisma just like sqlize allows us to write a sort of minimal query that uses table joins to give us exactly the data we want right so if we go back to the documentation and before we do that let's go ahead and comment this out and then get rid of all of this all right so go back to the documentation and what they did was they added a single uh user and then they have a query to include values for that user and actually i want to use something a little bit different here because we're dealing with a many-to-many relationship and in this example they were dealing with a one-to-many relationship right a user has many posts but a post doesn't have many users so and i'll include this link in the um in the description below the video there's a part of the prisma docs that includes information on modeling and querying many to many relations which actually wasn't easy to figure out compared to uh sqlize that was the one thing about prisma that gave me a bit of trouble alright so if you go down they talk about explicit relations and they create a value and then they show you a query so grab this and we'll put that right here change our model value we're looking up users that's just user okay now we're going to include and then we want to include what not tags of course for a user we want to include projects now sorry here there projects all right that's what we want to include so change this to project all right and then we want to include for the projects and remember what projects are according to our schema according to our schema projects are or is this projects here is a list of project assignments or an array of project assignments and inside of a project assignment we can get an individual project so we need to select this out of our project assignment model so if you go back here we're going to include project all right so we include all of the project assignments and then we include the project as well so we're doing a sort of inner join here we're getting that project table connected to the junction table which was project assignments and then attaching that to user so again that's a lot of talking so let's just go ahead and do this and sorry we should define variable value here let's call this result okay let's run this query and so you get a lot of data right and you get that because for each user say for octavio right you're getting his id of course name email password the timestamps now you've got his list of projects but that's going to include information from both the project assignments table and the project table sorry so we're getting time stamps for the project assignment we're getting a project id user id these come from the project assignment table and then we're going to go for the individual project and this comes from the project table we get the project id the project title and the status right so in this case we're getting the project id once twice and well that's enough isn't it i mean twice is still too much we're also getting the user id twice so what we can do to streamline our query and we can borrow a little bit of code from the documentation so go back right underneath that query that they gave us here they gave us a little function that maps over that result and gives us specifically only the project information and no information from the project assignments table so right above your console log you can add that in all right so we don't want to use result twice we'll call this all users now the thing we're mapping over here is this result right here so you just type in result and then we're saying for each user all right we're adding in the usual user values everything that's defined in the schema model right and then for all the projects which are project assignments we're mapping over the user projects and then for each assignment we want the only the project okay so no air so this should be good again i know this seems a little bit difficult to follow but and if you're new to prisma it's a little bit tricky to get used to how they set things up but it's a very nice streamlined query so basically you're getting that this huge big response right here and this is only for like three users right and then you're mapping over that response and then for each user right you're getting their basic user values and then you're also getting that list of project assignments but since we don't want all of the data from the project assignment table we're mapping over that list of project assignments and then just grabbing out for each individual assignment the project information right which comes from the project table right that's what we need to return to our graphql endpoint through our resolver right so let's go ahead and run this all right so you can see here we've got for octavia we've got his id his name sorry about that his email his password the timestamps then we get to projects and only for for the projects all we have for each project is the project id the title and the site upgrade or sorry the um status the timestamps and then we're on to the next project we don't get all that extra information from the project assignment table all right so you get a nice streamlined query and you this will work exactly with our graphql endpoint so what we can do is rather than use all of this stuff here and since this is a graphql uh project you don't need to be closing uh disconnecting your prismaclient every time like they had it set up to do and let's create a function called get users and export it take this bit of logic here paste it in all right we don't need to console log it but we need to return it all right and then our resolvers file should be good if you go back and look at it right we're just importing the get users function right and we hover over it and we see we're getting what we need to get right at least we know that the type is correct and then we're just returning that to our graphql endpoint so if we run our dev server we should be able to go to our playground and make a successful query that gives us our user basic user information like id name email address and then also the list of projects with all of the relevant field values there so let's go ahead and run our dev server all right so probably we forgot to take care of our connection here so first of all to fix this we can probably just change our schema to a typescript file all right let's um go into our index.ts file all right so this is a bunch of stuff that we're not using anymore so you can get rid of that won't need any of this all right so recall in the last video we were doing sqlize.sync here and using our models to create our tables we're not doing that anymore because we're now using prisma alright so let's go ahead and run our dev server or attempt to one more time all right so let's go to our playground right and just clear that out and we'll start from scratch all right so we'll need the id name email password no way you don't want to return that what are you doing all right projects right in our projects each of them have an id a title and the status all right so hopefully this will give us our response the response that we need so let's run it and boom we got it all right so again for each user we get an id a name an email and a list of projects and that's for octo octavio he has two and then for farah she has just the one project and then for peter who we said was on vacation extended vacation he's got no projects he's probably on a nice tropical beach somewhere enjoying his time all right so that's it that's how you work with uh prisma in a you know simple graphql project like the one we have it's very easy it's very powerful like i said if you already have an existing database you can just introspect it and automatically generate your schema right but if you don't have a database and you're starting from scratch that's no problem right all you need to do is set up your schema here now this takes a little bit of time right because you need to get used to how prisma uses schemas especially for a many-to-many relationship like the one we have here between project and user all right so i've actually made a video on doing many to many relationships with prisma and i'll put a link to that video in the in the description below the video so that way you can see how to set up a prisma schema from scratch but anyway we're going to be using prisma going forward with this project so i hope that you you can appreciate the power of prisma prisma 2 basically and you know i think we're all going to be early adopters of it and maybe um we're really on to something good something that's going to really change things going forward and maybe in a similar way to the way graphql changed things anyway thank you for joining me as always and i'll see you next time
Info
Channel: willjw3
Views: 1,605
Rating: undefined out of 5
Keywords: graphql, typescript, javascript, prisma, node.js, web development
Id: aqp8B_lekDE
Channel Id: undefined
Length: 36min 46sec (2206 seconds)
Published: Sun Apr 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.