How to Use Data Transfer Objects (DTO) for Validation in Nest.js | by Kevin Vogel | Feb, 2022

Know how DTO works

Kevin Vogel
Photo by Fernando Hernandez on Unsplash
$ npm i -g @nestjs/cli
$ nest new nest-dto-validation
$ cd nest-dto-validation
$ code .
$ git add .
$ git commit -m "chore(): init nest.js"
$ npm i class-validator class-transformer
src/main.ts
src/main.ts
$ touch src/app.dto.ts
src/app.dto.ts
src/app.controller.ts
src/app.controller.ts
$ curl -X POST http://localhost:3000 -H "Content-Type: application/json" -d '{"age": 1, "name": "Elon Musk", "acceptedTOS": true, "nums": [2]}'Server Response:{"age":1,"name":"Elon Musk","acceptedTOS":true,"nums":[2]}
$ curl -X POST http://localhost:3000 -H "Content-Type: application/json" -d '{"age": "1", "name": "Elon Musk", "acceptedTOS": true, "nums": [2]}'Server Response:{"statusCode":400,"message":["age must be a number conforming to the specified constraints"],"error":"Bad Request"}

Leave a Comment