NestJs Validation Tutorial 2021

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys my name is vlad and welcome in this tutorial we are going to learn about the validations in nsgs so what are validations validations is just some logic that you run on the data that your server receives from the client let's say you want to create a user and that user needs to have an email he needs to have a password it needs to have maybe a id so validations will allow you to throw an error and validate the inputs that the user sends to your server before you run any more complex logic so it's just a easier way to do it a straightforward way to do it so let's see a bit how it works and i'm going to use that opportunity to use my my wacom here and let's see so you have a request right your request coming from your from your client to to your server and let's say that you want to create a user and it will have for instance an id it will have an email it will have a password well what if um email is not there or password is not there if you run that logic if you run that input that data on on your business logic in your services you might run into errors so it's a good practice to actually validate this this data before you can execute any logic so for instance create a user with that given email and the password and stuff like that so this is where validation will come into play so that data it can be a body for a post request it can be a query for a get request or even post request it can be params and we are going to see all of those in details a bit later but for now let's just talk about the high level concept you have your data that is coming from the clients from your browser then this data will go through a validation logic so you have a validation and that validation will throw errors if something is incorrect and then this data will be mapped if we're talking about a post request for instance it can be mapped to a dto a data transfer object so this will be mapped to a dto and it's just an object that allows to to uh to map that data uh to itself so we are going to to see that in details a bit later so let's jump into into the code right now and let me zoom a bit i hope this is zoomed enough so again all this code is available on github in the link in the description below so feel free to clone the repo and follow along i have a very simple project starter from sgs the only thing that you need to see here is that i'm using a global pipe and validation pipe this will allow me to use validation pipes and validation logic basically in my controllers then i have a controller right and let me let me maybe zoom a bit here let's go it's okay it's better and we have some routes here and let's start with that so validation will allow you to validate the inputs that the user sends to your server right so we can apply a validation to to the param so something like like for instance putting an id in the url or a query so something like like that for instance or a post request with the body and this is where we will use details let's the server is already started so let's try to call that route and see what happens here i want to stress out what is going on here so we have the console log i'm constantly logging the id and i'm console logging the type of that id so here we say that we expect a string and let's see if we have the right data so i'm going to open insomnia here and i have the the route here let's call it and you see that i have a console log here so i have id one and the type of that is a string and this is totally normal uh so if i change it to number and i restart the server and i do it again well it will still be a string so if we want to convert that string to a number we can use the validation pipe so it's something like parse and pipe right and then if we if we do if we send the request it will be converted to a number so that's a quick way of converting the inputs and that is working irrespective if we have the validation pipe enabled or not so if we do it again it will be converted to a number let's try the queries now so it's the second route and it's query parameter and id one so if i launch it it will be a string so again if i if i convert it to uh to integer it will work correctly and i will get a number so that's one way you can explicitly convert it to the integer you can also go into the validation pipe and tell that you want the transform to be true so that will actually uh help you to convert any primitive type to the one that is indicated here so if we indicated that we want a number it will try to convert that that that that data to the number so if we do if we do the request it will be a number and we can try the same with the parameter out so we can get rid of the parse in pipe here and since we have transform set to true it will try to transform the primitive type to the the type that is uh indicated here so if we launch that route which is a parameter out and let me zoom a bit maybe it will be a number and if we try the query route it will be also a number so the transform uh property here allows us to transform the um data that we receive from the params query or even body to the data that we have indicated here and it's a primitive data so it can be a string a number something like a boolean it will try to transform that however if we have something a bit more complex this is where we will use dtos you can also use details here in the query if you have different different i would say properties for instance like ide sql one type is equal admin and stuff like that however most of the time you will try to use dtos on um on on the body object so here i have created a dtu i just named it dto and the dto is called post route dto and i have put that in a folder here it's called post route we have a baron export here so i just export all the all the details um from the um folder that will allow me to actually import from the folder and not specify every time like a more more precise route this is a technique i use quite often it's called baron export i think and here we have adtl so it's just a class you could put an interface right but uh with with the interface you could not have validations so to have validations we are going to use a class and we are going to use class validators so here with classified data with the creators you can indicate what kind of properties it should be so here it should be a number here it should be an email here it should be a string and let's call that route in in insomnia you have the post route here i provide a json object in json basically that will be mapped to the dto so to the object here data transfer object this the whole concept of the dto is just that you have an object you can map data to uh you can run a validation on that object so it's something that the programming language can play around and and manipulate and stuff like that this is the main usage of the dto and you can pass the dto to to the service and the service can execute logic on it as simple as that so um let's run that query so we send it here and we have the dto here we logged it here uh id one email um well email and password one two three so if we uh provide something incorrect for instance uh the id is a string it will throw an error it will it will run the validation on that on that object and it will say id must be a number and you have provided me a string that's not good right so if we provide a number it will be happy again and it will log it here so that's the whole purpose of the details it can really quickly along with validations um kind of verify the the data that we pass to the server the dto is just an object it does not verify anything by itself it can be created through from an interface or from a class but the validation in itself is basically those those decorators for the dto and and those pipes if we want to to put them but here since we have said that the transform should be uh should be true it will try to transform the data like directly to the into the data type that we need so if we go here for instance if we provide not an email we provide just some value it will complain that it needs to be of type email and that's pretty much self-explanatory now let's say that i want to i injected something else right something that the server does not expect for instance type is equal admin right and if we run it well you see that we log that data here although it was not declared in the in the data transfer object here but since um behind the scenes it's just javascript you can literally map anything to to any objects so that would be no problem so to avoid that and the reason why you want to avoid that is sometimes i use something like um let's say i want to create a user so for instance it will be um sorry here new user and i would be i would do something like um object that assign let's say you have a user object from from a um a from typo or prisma and i would do something like that so that instead of doing like new user dot email right is equal dto that email and new user dot password you see called the detail instead of having something like very verbose like that i can literally reduce that to one line especially if the ddo has something like 15 fields right so that is very handy and i can just do something like that but for that i need to make sure that the dto has exactly the values i need so that they are correct that they are validated and everything so in order to make sure that the type here is not injected by the user we need to add some more properties to our to our global validation pipe so let's proceed i go to main.ts i'm just going to restore the state here because i have committed the changes already to the to the repo so we have transform sql true white list this is what we need white list will allow us to strip out all the properties that are not defined in the dto so if i have not defined type well the property type will be stripped out stripped away four bit non-white listed that that just means that it will throw an error if i try to to provide a a extra property it's just useful in development so when you develop you want to see if you have accidentally not sent something that you should not be sending so i put that to true and i just disable the error messages in production so so because i don't want the user to see that right so i'm going to disable the error messages if it's in productions so that's pretty self-explanatory and let's try again so if we come back here and we type admin well it says property type should not exist right so if we just disable the errors here it will just strip it away and there will be no type so that is very handy this is basically validation folks make sure that you actually clean this folder because sometimes it can be cached and i have run into that problem myself where i was adding validations and the this folder was cached and nothing was happening like it was not behaving the way i wanted so always make sure that something is not working really it's probably the cache and you can just delete it and rerun uh nest gs and it will regenerate that this folder with updated values so that's all about validations in a way like the main purposes of validations is to validate the input that you the user sends to your server and do it in a quite um elegant way right so you don't write a lot of logics for instance af dto that id if not dto.id throw an error or something well instead of doing like that which is very very verbose and very annoying you can use those validation pipes and the validation dtos data transfer objects if you have any questions feel free to drop them in the comment section below and see you later
Info
Channel: Code With Vlad
Views: 2,066
Rating: undefined out of 5
Keywords: nestjs, validation, tutorial, javascript, typescript
Id: e60Y1p2hEBE
Channel Id: undefined
Length: 14min 55sec (895 seconds)
Published: Sun Jul 25 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.