Validate Income And Outgoing Parameters In NestJS
We always should care about what kind of data is coming to our REST API. sometimes we need to remove extra parameters, and sometimes we have to check types. some variables should send as a number some of them string or maybe time or URL.
The problem is if even we do validate for incoming data, most of the time we forgot to validate our response. but:
Why Validate Outgoing parameters? As some consumers are consuming our response, we should be careful about what we are going to change in some existing code. probably by our changes response will change. Sometimes we remove or add a new parameter which can break our consumer.
Before starting to write validations, we should add a pipe to our project to catch the incoming errors from validation.
To that purpose, we need to just the following line to the
const app = await NestFactory.create(AppModule);app.useGlobalPipes(new ValidationPipe()); <------ Add this lineawait app.listen(3000);
First of all, let’s assume that we have a form which is responsible to get the data from the user to register him/her in our database.
Fields which we need are like the following code (you can find the completed code at the end of the section) :
number age; // age can be optional
For the incoming data, we have to create a DTO file for each endpoint, for example, here we have a
The next step is installing the related packages to verify the DTO
npm install class-validator class-transformer
Typescript by Itself is handling the decorators. so like the following code we easily add the validation for each parameter:
class-validator supports many decorators and for each of them, it has many options. So, I recommend you have a look at their documentation https://github.com/typestack/class-validator.
The issue with outgoing is we have to call the verification function manually, before sending it as a response.
So, the first step of the process is to convert the object to a class by the
class-transformerpackage. The following code can convert your object to a class and throw an error if there is any.
The next step is extending our current DTOs by our verification class and then easily calling the verification function before passing it as a response.
Here, It’s how we are going to use what we have in a sample controller
I hope you find out this article useful, ask me if you have any questions and follow if you want to be like a pro ✌️
Here, I provided a video to create a verification function for incoming and outgoing parameters in Nest.JS, also we will test more decorators of class-validator there