Set Validations for a Model3:09 with Guil Hernandez
Let's begin setting up validations and constraints for the User model to prevent invalid data from being entered into the database.
Let's begin setting up validations and constraints for 0:00 the user model to prevent invalid data from being entered into the database. 0:03 As I demonstrated in the previous video, 0:08 null by default is an allowed value for any attribute or column of a model. 0:11 Sending an empty post request or even setting a property explicitly to 0:16 null allows User.create() to be called here in the post users route and 0:21 successfully create a new user entry. 0:26 We don't want that. 0:28 First, we'll make sure that a null value is not allowed for name, 0:30 email, birthday, and password using the Sequelize allow null check. 0:34 If any of these attributes are null, 0:39 the new user entry will not be stored and a validation error will be thrown. 0:42 Inside the name attributes object, 0:47 I'll add the allowNull option and set it to false. 0:51 I'll do the same for email, then birthday, and finally password. 0:56 Over in Postman, I'll try to send a post request to the API 1:11 users routes with missing attributes or 1:16 fields in the body, an empty object for example. 1:19 Notice how I receive a 400 bad request HTTP status code back from the server. 1:23 And the response body displays the validation error messages thrown by 1:29 sequelize, preventing unreliable data from being stored in the database. 1:33 So here in the post users route handler function in routes.js, 1:37 the error is thrown in the try block, user.create does not get called. 1:42 So the statements in the catch block execute instead. 1:48 I've also added a console.log statement here in the catch block, 1:52 where I'm logging error.name. 1:56 So we're able to see the error being thrown. 1:58 Notice in the terminal that the error log is a sequelize validation error. 2:01 As you've noticed from working with sequelize in previous lessons, 2:08 the format of its errors contains more information than what's typically 2:12 necessary to return to the client. 2:16 So for this workshop, 2:18 I have also transformed errors to a more straightforward format by first 2:19 checking if the error caught by catch is a sequelize validation error or 2:25 a sequelize unique constraint error, which I'll talk more about later. 2:30 Then I'm iterating over the errors array that's in the sequelize error 2:35 passed to the catch block to access only the error messages and 2:41 sending the error messages back to the client, 2:46 as you can see here in the response body. 2:50 Else any other error will be thrown here and caught up here and 2:54 the asyncHandler function that wraps each route. 3:00 More about this handler in the teachers notes. 3:05
You need to sign up for Treehouse in order to download course files.Sign up