NestJS で加算 (Validation 付き)
5927 ワード
こちらのプロジェクトを改造しました。
NestJS の DTO と Validation の使い方
次のような結果が得られます。
1) 引数が正しい場合
$ http post http://localhost:3000/items aa=23.58 bb=45.19
HTTP/1.1 201 Created
Connection: keep-alive
Content-Length: 5
Content-Type: text/html; charset=utf-8
Date: Fri, 19 Feb 2021 10:59:58 GMT
ETag: W/"5-FuGR3NAEdByFKIjVXtIXUF1c3VA"
Keep-Alive: timeout=5
X-Powered-By: Express
68.77
2) 引数に誤りがある場合
$ http post http://localhost:3000/items aa=23.58x bb=45.19
HTTP/1.1 400 Bad Request
Connection: keep-alive
Content-Length: 81
Content-Type: application/json; charset=utf-8
Date: Fri, 19 Feb 2021 11:00:37 GMT
ETag: W/"51-Zwzc1rgvcjQ66LJW52ouMEqR5Yk"
Keep-Alive: timeout=5
X-Powered-By: Express
{
"error": "Bad Request",
"message": [
"aa must be a number string"
],
"statusCode": 400
}
改造したのは、次の2つのプログラムです。
src/items/items.dto.ts
import { IsNotEmpty, IsNumberString } from 'class-validator';
export class CreateItemDTO {
@IsNotEmpty()
@IsNumberString()
aa: number;
@IsNotEmpty()
@IsNumberString()
bb: number;
}
src/items/items.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { CreateItemDTO } from './items.dto';
@Controller('items')
export class ItemsController {
@Post()
createItem(@Body() createItemDTO: CreateItemDTO) {
console.log("*** createItem ***")
var aa:number = Number(createItemDTO.aa)
var bb:number = Number(createItemDTO.bb)
console.log("aa =" + aa)
console.log("bb =" + bb)
var sum:number = 0.0
sum = aa + bb
console.log("sum =" + sum)
return sum;
}
}
Author And Source
この問題について(NestJS で加算 (Validation 付き)), 我々は、より多くの情報をここで見つけました https://qiita.com/ekzemplaro/items/48505cdcab552b1b628c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .