Create an API via NestJS Part IV

Validation error for CRUD

Create validation function for the Read method

Go to quiz.servise.ts and edit the read() function such as:


Line by line explanation:

  1. Declaration of the read() function which takes id with string type.
  2. Writing a response from a database to the quiz constant.
  3. Checking whether the quiz constant's value is 'null'. The condition will be true if the quiz is undefined or equals to 'null'.
  4. 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.
  5. "Else" statement.
  6. 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

touch src/shared/validation.pipe.ts

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: