Validation error for CRUD
Create validation function for the Read method
quiz.servise.ts and edit the read() function such as:
Line by line explanation:
- Declaration of the read() function which takes id with string type.
- Writing a response from a database to the quiz constant.
- Checking whether the quiz constant's value is 'null'. The condition will be true if the quiz is undefined or equals to 'null'.
- Throwing a new exception. It will be handled by our logging interceptor from the previous part. HttpException is the function of two arguments: the first one — a message which will be shown when error threw, second — just server response code like a 404 for Not Found or 200 for OK.
- "Else" statement.
- Returning data that we received from the database.
Do the same for Update and Delete methods
Create a class validator
Install the necessary packages:
yarn add class-transformer class-validator
And create file
Now just copy code from the official documentation, and write some fixes:
Rows 14-19 — validate did we receive an empty object.
Rows 28-31 — pass the errors to logging interceptor.
Rows 41-49 — aggregate all errors into one string.
Rows 50-56 — a function that checks if an object is empty.
Then we have to change our DTO file to be able to validate fields:
Finally, connect your Validation Pipe to the controller: