Full Stack Web App using Vue.js & Express.js: Part 2 - Sequelize

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone I'm Cody Sanford and welcome to part 2 of building a full stack web application using view GS and Express jeaious so if you remember on the last part one we built a register page which hits a slash register endpoint on the server so in this part too one of the things we're going to do is actually connect to a database or have our API connect to a database and in this case we're gonna be using sequel eyes which is an ORM to connect to like sequel related databases such as like my sequel or Postgres or sequel light a couple people asked if we could do MongoDB but I also I feel like you know sequel databases are still one of the most popular ones so I think it's more important to learn how to use sequel vs MongoDB and also I think the data that we're working with is a relational which is another reason why I think we should be using sequel eyes to connect to a database to store these relational models alright so before I get started with bringing in sequel eyes let's go ahead and look at it really quick so inside the sequel eyes project they have this these Doc's defined these Doc's are pretty good they're not the best but um if you read through these you can get a good understanding of how you use sequel eyes you know how you define models how you can use models but basically then it in a summon up sequel eyes provides you with data models or each model maps to a table in a database so for instance if you wanted to create a user model that has a email and a password you can just create a sequel eyes model and then will automatically connect to whatever sequel database such as sequel light it'll create your tables and then create your columns for that table and then you can use objects inside your node or Express server to kind of manipulate that data or add records or remove records etc it's kind of a fall I'm gonna cover with the sequel eyes documentation so let's just go ahead and get started using sequel eyes so start off we want to first install those dependencies so on the right I'm going to say NPM install save sequel eyes and then we also want to include sequel Lite 3 and I'm gonna do version 1 3 8 just because I ran to an issue in the past with a newer version of sequel 93 so anyway when that stuff is done installing it shouldn't take too long what we can do in the meantime is we need to first kind of get our project set up to start using that sequel eyes package so to start off we're going to go ahead and pretend like we have a file called models which is going to export a sequel eyes object so if I do a consequence equals require dot slash models spell that correctly so basically we're assuming that there is a models folder which has an index J s file which returns an object that has a sequel eyes attribute on here and what we want to do is just go ahead and do sequel eyes that sync which will basically connects equalise to whatever database that you have it configured for and then create the tables if they don't exist and just get everything that's set up and ready to go and once you're done sequel I are syncing sequel eyes to your database we're gonna go ahead and just start our server and to kind of make this more useful when the server starts just go ahead and print out a message so we can actually know when it started so I'll say console log server started on port and I'll say config port and then here I'm going to refactor this a little bit and it's just say config port you'll notice that we don't have anything called config defined in this file so up here was a Const config is equal to require slash config slash config so the first thing I need to do is create a new folder called config and I'll create a file inside that folder called config j/s and insights config yes I want to export something that says port 8081 so no app DOJ's can include that file and they kind of use whatever is defined in that couldn't fig to spin up the application another refactor I'm going to do before I actually start working more into sequel eyes and defined the models is if you notice here we have the to find it's kind of useful if you have a separate file where all your routes are defined so what I'm going to do is in the source folder I'm going to make a new file called around Jas and that's going to export a function and basically what we're going to do is cut that code out and put it inside that wraps funk car that um routes a jeaious module save that file and then here what we can do is just go ahead and require that file so I can say Const our sector to say require routes and then I'm going to pass it app because I remember our routes file basically just returns the research returns a function for us where we can pass an app and it's going to just go ahead and attach all the different endpoints on to that application or that Express application variable alright so by this point sequel eyes and sequel like three should be done installing which it is so I'm gonna go ahead and just close out of that tab and then additionally we're seeing an error print out because the routes file does not have a new line at the end of the file so I'm just going to fix that really quick do the same thing with config okay so it says right now can I find module models because we haven't even declared that yet so that leads us to the next step of part two which I'm going to start building up a a user sequel eyes model so to start off let's just go ahead and make a folder called models and inside here I'm going to make a new file called user J S which is going to be my user model so the first thing you need to do is if you read through this equalized documentation you can kind of figure out how you define sequel eyes models and we're going to do a little bit of custom logic and linking for our models so that we can uh kind of easily put new models into this model folder and I'll have to worry about importing that somewhere else so what I'm going to do is I'm gonna say user J s is a file which exports a SiC a function which takes sequel eyes and data types and then what this is going to do is then we're going to use sequel eyes to define so you do sequel eyes off define a new model so the first argument is the name of your model and which is gonna be user and it's gonna be used for storing user related information so first one we want to serve the second argument here this is are the options or attributes that are attached to your table or model so the first attribute we want is email because you know you sign up with your email and password so say that's going to be called email and the type is going to be a string and then we're also going to say that this is required to be unique because we don't want multiple users signing up with the same email account and then the second attribute we're gonna say is going to be called password and it's also going to be a string so at this point again user rjs is a function which takes sequel eyes and takes datatypes and then it's going to return or define a user model which we can use so now the next step is if you remember in the apologia so we included slash models so we need to create a index.js file and inside this index.js file we want to do a couple of things first we're going to declare a DV object which we're going to export later on but more importantly we first want to include a FS module which is the nodejs way of like reading through the file system we're going to include the path module which is used for kind of dealing with you know absolute paths relatives paths or whatever it's so we're gonna use that in conjunction with FS we're gonna include the sequel eyes model because we're going to need that to actually create a sequel eyes object and connect it to a database we're going to include that config file that we created earlier and okay so at this point the first step we're going to do is we're going to decline I declare a sequel eyes object so we can say a consequence is and that's going to take in a couple of arguments so the first argument is going to be the database that we're connecting to so let's just assume and config we have something called DB database and we can also assume that we have something called user we have something called password and then lastly we have additional options that we can pass to sequel eyes so at this point what we can do is we can go in to that config file and I'm going to go ahead and declare a DB attribute which is going to have that database it's going to have user got a password it's going to have options so for database we're going to load in a couple of environment variables and fall back to tab tracker so this is the name of the database that we're going to use so typically if you have like my sequel or Postgres you create a database so your Postgres instance is going to have like a hundred different databases inside of it database has a unique name so we're say database is equal to this environment variable DB name or tab tracker and we're going to use this later on when we like deploy to a real environment but it's good just to have this here in the mean time and if it's not defined we're going to fall back using a work to tab tracker and the same thing with user will say DB user password processing the DB pass and that's also just going to be tab tracker for local and then finally we made two options there's three things needed define so first is dialect and that's a useful option in sequel eyes to tell it what type of database you're going to be connecting to so obviously we want to set that to this equal like when we're local we have host and that's used for telling sequel eyes the location of the database that you want to connect to so in this case we'll say localhost is the default and then lastly we want to put storage for sequel light and that firm it tells you where to store your sequel light file so I'll say tab tracker sequel light cool so at this point we have again a config file that declares the port in fact I'm going to do process env port or 8081 so we can overwrite that as needed and then we have an attribute called DB which has all the different sequel eyes related configuration we need so this if I go back to models folder and then index ajs you can see how this makes sense that we're just grabbing that config and passing it to the sequel eyes constructor here so now the next part is we want to just go ahead and write some short functionality to just automatically read through all the models in this models folder and set it up to be useful sequel eyes so I'm going to go ahead and do FS dot read sync and then passenger name so basically this is going to read through the current directory and give us an array of different files and then I'm going to filter out any file that is equivalent to index on J s so we don't we don't want this index file but we want every other model file and then after we do that filter we can just say for each file that we found we want to go ahead and declare a model and basically sequel eyes has a import method where you can give it a full path to a file and it'll go ahead and just import that and set it up to be used with sequel eyes so I'll go ahead and use path join to join the der name to the pet file and then tell sequel wise to import it and then finally we can say set the DB name of the model so in this case would be DB dot user is equal to model and then lastly we can go ahead and declare a couple of useful variables on to this DB object so I'm going to declare DB sequel eyes and capital sequel eyes so that when we use this in our code we have access to the sequel eyes object we have access to the capital sequel eyes object and then we have access to the actual models alrighty so at this point let's go ahead and make sure that you know we don't have any linting issues okay so we solve that the server restarted itself when I save some of the files and then it executed this sequel command has said create table if not exists users and then it gave that table a couple of columns such as email and password and that's about it so basically sequel eyes will create your table if it doesn't exist and give it the columns that you've defined in your model and that was pretty easy to do like a lot of this stuff like this we didn't even need to do but it's more of a helper function that allows us to easily add more models down the road without having to like for each one require it import it and set it up and sequel eyes ok so again as a recap we installed sequel eyes so if you look at package shot JSON we installed sequel eyes and sqlite3 cycle eyes is an ORM used to connecting to SQL databases and sequel id3 is a local instance of a sequel database without having to go through all the extra work of setting it up and whatnot and then once we install those we were going to we went ahead and created this models folder which has a sequel eyes model which we're going to be using for our user accounts which has an email and has some password and then we have this index file which is basically used for connecting to our database which is going to load in a couple of configurations which is defining our config right here and then it's going to go ahead and read all the files that are in this models folder that do not equal index on j/s and it's going to go ahead and load them into sequel and then we just go ahead and return that which we can use later on so at this point hmm we can actually start modifying our route to use this equalized stuff so another thing I'm going to do let me close out of all these tabs so we're acquiring routes here so if I open up the routes file I think we're done with app dot J's for a while something that is useful and you'll see this on a lot of frameworks is they are going to have a folder called controllers and a controller is basically where you have all your endpoints defined so inside controllers I'm going to go ahead and create in authentication controller J's file and inside this file we can go ahead and just export our model or export whatever routes should be associated with authentication so in this case we obviously want to have a register route right so if I were to do this and just put that same function let me just get rid of this stuff so basically I took the same function that was defined in routes and I put it in register but we're only caring about the callback function right here which is they Express endpoint or middleware or whatnot and then what we want to do is in routes we can up here just go ahead and include that so we can say Const authentication controller it's equal to require controllers authentication controller so then whenever we hit this register endpoint we can just say authenticated authentication controller dot register so this is a nice way to kind of simplify and keep everything isolated so your controllers again are used for declaring all your endpoints and then your routes are for declaring your routes that point to your controllers so again just to make sure this works let's go ahead and hit that register endpoint and make sure it returns that message and it does everything's still working as expected so now we can actually start implementing some logic to kind of create a user model and save it your database when someone hits this register endpoint okay so we take a step back and just talk about what we're trying to do or if you remember that from the front end the user is going to pass us an email and a password in the payload of the JSON alright so on rec body we should have an email and a password and we already demonstrate that we have email here because we're returning that message so what we are trying to do is we want to create a new user record in store into our database whenever someone hits this endpoint so first of all let's go ahead and insert or not insert but let's import or require that user model that we declared so we can say cons to user equals require dot dot model or actually this would be ma tools because we're going to include that index file J s which had all the models declared as attributes on this object so now we can actually use that user object here that we defined inside of our callback so what we can do here at this point is we could say cost user is equal to a weight user dot create record out body now I'm going to go ahead and get rid of this stuff for now and of course I'm going to use async instead of promises because it just makes everything cleaner so basically we want to create a user using the body that was passed in on the request and that will create us a new user and if for some reason there's any error such as you know the user our email already exists we're gonna get catch it inside this try-catch statement so if we get in here we can say res dot status is a 400 error and then go ahead and send in some type of error message so in this case I'll say this email account is already in use and you've seen that in front ends where you try to sign up for the same website with the same email account and I'll tell you like you know this email account is already news so this will be returned to the user if this fails to run for some reason and then if it is successful we can just go ahead and send back that information so I'll just go ahead and say residents end-user to JSON to basically send back that user object to the client who has requested this endpoint so go ahead and save this file make sure that there's not any lending issues or crashing the server seems like everything is fine and what we can do at this point is if I go to register and I go and try to pass it testing at gmail.com it should return a 200 status with that user object that was created all right so now this is actually inside the sequel I'd database we actually have a user so if I were to try to do this again we should get that catcherror back and says this email account has already in use so that's pretty cool I mean we have a server running that's connected to a database using sequel wise we're able to store information inside the database at this point we can't really grab it yet from any endpoints but we've demonstrated that yes the data has been changing because now we get this error account our error message back when we try to create an account with the exact same email and again the reason why that constraint is failing is because in the model we added line 5 which is unique true saying that the email has to be unique so it can't already exist inside that record ok so at this point you may say ok well if I were to trying to pass in a bogus email account so like 1 2 3 to this in point it's still gonna work it's still gonna try to create an account with that email so another useful thing to do to have on your back-end is validation so what we're gonna do at this point is let's go ahead and make or include another framework called joy so did npm install' save joy and joy is a framework used for validating the request dot body the request query or the request dot parameters and so as an example of how you set that up typically in these bigger frameworks you're gonna have like another folder kulluk policies so I'm gonna go ahead and create a folder called policies here and I'm going to go ahead and create a and authentication controller policy and inside this file we want to kind of create Express middleware which is going to validate that certain requirements or data constraints pass or fail so to start off we'll say module dot exports and then we're going to export the name of the exact same method that we've used in our controller so call it register it's gonna be a function which takes req resin next and what we want to do is first we need to include that joy framework that we just installed which should be done by this point yep it is so I'll close that and then we also want to go ahead and actually that's all we need to do right there so again we included the joy framework we created this module which has a method and for now I can just say call next and how do we actually use this right so if you go back to routes we can include this up here in say content ocation controller policy it's equal to require and I'll just say policies so I'll go ahead and require that in and then what we want to do is call that policy as a middleware function before we hit our controller so how this works in Express is we're gonna hit this in point and it's going to continue to go down the list and invoke whatever middleware that you have defined so it's going to hit this controller policy dot register file which is declared here and then when this method calls next it's going to go ahead and go to the next line which is going to be our registry endpoint which again is defined here so again this is Express middleware you can read more about it on their documentation page and I think it'll make more sense as we continue making more importance down the road so what we want to do inside this middleware function is we need to validate that email and password kind of match a couple of constraints so the first constraint we need to do is we need to Const schema is equal to an object and in that object we're gonna have email we're also going to have password an email is going to be required to be a string and it's also going to be required to be an email format so Joey has a bunch of different like built-in pre-baked validations an email as one of them so we're saying email has to be an email and then password we can say make sure it's also a string and make sure it matches a particular regex expression so I'm just going to pass a new regex expression and what we want to do here is pass it character class of a through Z capital A through Z or 0 through 9 and course make sure it's at least 8 to 32 characters long and then go ahead and put any money sign to end that string so I think my I think I did that correctly so basically again email has to be an email address and then password has to be a string which matches this regex expression and again if you don't know much about regex you should probably go read up on regex basically we have these classes which say everything that's passed in has to be the character lowercase a through Z uppercase a through Z or 0 through 9 and it has to be a minimum of 8 characters in a maximum of 32 characters so after we have this schema defined we need to actually use it so we can say Const error value is equal to joy not invalidate and the first parameter you do for validate is you need to pass it the thing you're trying to validate so in this case we want to validate the request body and we want to validate it against our schema so this will return an error if there was an error so I'll say if error else we just go to the next so basically if there's no error everything's good we just go to the register in point and register that user if for some reason there was an error we need to figure out which validation failed so I'll say switch error details of 0 context of key so that gives us the key that failed in this case it's gonna be either email or password and then we're going to have a switch case and just check if it was email we need to do something if it was password we got to do something and then default do something else so starting off if for some reason the email validation failed we could say res off status of 400 and then go ahead and send an error message saying let's say like you must provide a valid email address cool and then for password similar thing but we're gonna say this time let's just return a little bit more information so let's say the password provided failed to match the following rules and then we'll just make this HTML so we can easily format this I can say it must contain only the following characters lower case upper case numerix and that'll say roll to is it must be at least eight characters in length and not greater than 32 characters in length so again if there is an error we check if it was an email error and we can send back you must provide a valid email address we check if as a password error and say you know the password has to match these rules and then otherwise we can just say like I don't know resident status of 400 send an error saying like invalid registration information so that should make sense let's just again do a recap we included the joy framework which is used for validating different things in express and then we created a module which has a register method which is an Express middleware which takes a wreck a res and a next and again wreck is the request that comes in res is what you use to send something back and next is what you call to invoke the next thing in the routes path and then we declared a schema which says emails must have an email structure passwords must match this Fredericks we validate the req body against the schema here we check the error we check the key of the error and return different error messages depending on what failed and then after that everything was good we just go ahead and call next so at this point I'll go ahead and save that file and I'll double check to make sure that we don't have issues so on the routes we have no trailing spaces I'm go to the routes file cool all right so now at this point let's go ahead and test out that the policy is working as expected and to do that we can again go back to postman and we can try to pass in bogus data so we're say passages testing it sends back in here you must provide a valid email address with a 400 bad request response and so if I were to give it a good email address and try to send it's gonna say the password provided failed to match the following rules so cool that's working if I go to 7 & 8 and send that it says this email account is already in use so I'll change that and see what happens so boom we were allowed to create a 1 to 3 at gmail.com with the password 1 2 3 4 5 6 7 8 and it returns us back the exact user that has been created all right so now at this point we have a pretty good setup for registering a user into our database and we have policies that kind of return errors so that the user knows what exactly is required we also need to at some point hash the password because you're not supposed to be saving you know raw passwords into your database what we can kind of cover that in a second so let's go ahead and move to the UI again so if I go back to that register component up here just a recap we had an input for email and input for password and we had a button to register ok so now that the backend is returning different error codes and messages we want to kind of display that in our user interface so what we can do is if we want to catch the error let's return to B go ahead and just wrap this in a try-catch so if for whatever reason authentication service fails to return or fails to for whatever sorry rephrase that for whatever reason an authentication service the endpoint returns a status other than like 200 or whatnot where you can catch that error here and we go ahead and say this out error is able to I'm gonna change this to response actually not say err so I'll say era dot response data dot error and this is basically what is returned from Axios and then error is going to be that message that we've defined and of course if we're going to try to access this on error we need to define it in data oops and then last thing we need to have print that out so up here if I above the button I could just do div and I guess a V HTML is equal to error I can just close up close that off here and again put a break I'm also going to say that this is going to be a class of error so down in the style I can say error is equal to color of red so I were to save this file now and then try to register some bogus data we get you must provide two valid email address change to a gmail comm the password you provided failed to match the following rules it seems like that kind of truncated some of the data so maybe this isn't like big enough let me just double check what's going on here hmm because it looks like it's returning okay so in my my back and you see there's a little missing a carrot here so let me just go back to my back-end code really quick to my authentication controller actually I'll go to my policy and I'll change that to that now if I try to hit the endpoint again boom okay so we get the actual full error message now cool so again as a recap I don't really explain the view components before but basically every dot view file is separated into three sections you have to go template which is used to define your HTML template and then inside your HTML you can have special attributes like be model or be HTML take technically anything that has a V - is they view specific attribute and that's used to kind of bind to your script tag down here which is the second part that every top view component has and the script is basically an object that has a different lots of different methods on it so data is the data that you can bind to way in one way to your template and then methods would be any type of method that you want to be able to access from your template and there's a couple of others which we'll cover in the future but it's just for now we just focus on those two and again the last one is your style section which is going to be in this case scoped so any Styles you declare here will not affect anything else on your few application assuming that you have scoped so dot error will only work for this template so again everything in view is really like compartmentalized and isolated so it's really nice let's try to think and again here's an example at clique means whenever the button fires a click event call the register method which is what you saw down in here that's how we're calling register Sarge's a little bit more information about the view component that I don't think I've really talked about in part one I kind of just started doing stuff without talking but hopefully by now that kind of makes more sense all right so for I think the last thing I'm gonna do in this part 2 video is I want to kind of bring in a new project inside the front-end to a lot of see easily style and kind of do layouts so there's a there's a project called beautify which is a framework that you can be used to build like material design apps mm-hmm so again their documentation is pretty good here on the left it has like you know all the components you can use so if I wanted to do like a grid list or a form they give you examples of how you do it you can go and check out their code here they give you a template I think you can see the code somewhere maybe not let me find a different one data tables here we go so again they give me an example of a data table you can go here and view the source code what you get is the template and they give you the script here mm-hmm so again beautify is just a framework that's used for building really nice material design apps so we feed it feel free to check it out and that's what we're gonna be using so what we want to do to include this in our application as we first want to go over to again our terminal and go to our client and we want to MPM install a couple of things so first of all we want to include beautify and I think actually that's the only thing we need to include is just beautify okay so now that that is done installing we can just go back to our UI and we want to include it so if we go to our main DOJ's file here up here we can just say import view to Phi from beautify and then we also want to import the style sheet so I'll say beautify dist beautify min CSS and then to kind of enable that we can say view use of ufi go ahead and save that and hopefully assuming I didn't forget anything that should kind of load in the project so now we have the beautifying in the beautify CSS ready to go so let's go ahead and try to style this there's some there's a cup of the design I kind of like doing is putting stuff in panels with like a drop shadow I'm not really a style or a designer so feel free to kick me or give me feedback so what I'm gonna do here is I'm gonna go to the register that view file here and beautify gives you the ability to kind of like change up your layout so they give you something called like be layout you can pass it like a column layout so I'll do P layout and this is pretty much um like flex box so this is a be like a flex grid or whatever and in here we can do V flex which is going to be a flex item and then you can change it kind of like a bootstrap where you can change it depending on the size of the screen we can say for small screens we want to offset it three and then just make it a width of six and then in here we can say mmm let's make a div and then the beautify CSS gives you a couple of pre baked CSS so we can give it a elevation of two and a white that's going to make like a white panel with a little bit of box shadow or drop shadow another thing we can get from using beautify is a V toolbar so this a B toolbar I'll pass it a flat and a dense attributes I'll give it a class of Sian I'll give it a tributo dark so that it turns the text white and then inside the toolbar again this is all in the beautify examples so if you just want to go and copy and paste from there examples you can do that too so let me just make sure I got this all right basically I can copy this code out and put it underneath here grab this in the div in case we need some padding and it also beautify get to a couple of classes so I can do like padding left is for padding right for padding top to padding bottom of to so make sure all these line up kind of running out of energy so I might wrap this up pretty soon so hopefully if I save this it should be a styled panel with register and then we have our email account and we have our password here and then we have a register button in the button we can actually change from button to mething V button so if I were to do B BTN give it a class of cyan should changes to a register button so that's I think good enough for right now we can come back and make this a lot nicer looking but I'm kind of running out of energy so stay tuned for part three and again as a recap we included the beautify project which again you can find the docs here and beautify Jas comm they have a bunch of different components and styles that are pre baked it's really awesome library so check it out and then we use a unify that kind of style this register panel and I think part three we can just try to fix up the styling and do more by adding like a header or side nav or something like that alright thanks for watching and stay tuned for part three should be coming in a couple days hopefully thanks for watching
Info
Channel: freeCodeCamp.org
Views: 93,401
Rating: 4.8962536 out of 5
Keywords: learn to code, programming, coding, javascript, web development, coding tutorial, javascript tutorial, web development tutorial, css, design, vue.js, learn coding, vue, express.js, express, node, sequelize
Id: xZMwg5z5VGk
Channel Id: undefined
Length: 44min 28sec (2668 seconds)
Published: Tue Sep 05 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.