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

Understand how DTO works

Picture 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/essential.ts
src/essential.ts
$ contact src/app.dto.ts
src/app.dto.ts
src/app.controller.ts
src/app.controller.ts
$ curl -X POST http://localhost:3000 -H "Content material-Sort: software/json" -d '"age": 1, "title": "Elon Musk", "acceptedTOS": true, "nums": [2]'Server Response:"age":1,"title":"Elon Musk","acceptedTOS":true,"nums":[2]
$ curl -X POST http://localhost:3000 -H "Content material-Sort: software/json" -d '"age": "1", "title": "Elon Musk", "acceptedTOS": true, "nums": [2]'Server Response:"statusCode":400,"message":["age must be a number conforming to the specified constraints"],"error":"Unhealthy Request"

More Posts