[英]Nest.js Multiple Query Parameters with Same Name
Controller控制器
@Get(')
test(
@Param('accountId') accountId: string,
@Query('propertyName') propertyNames: string[],
) {
console.log(propertyNames);
}
Sample Request localhost:8000?propertyName=test2&propertyName=test3
示例请求localhost:8000?propertyName=test2&propertyName=test3
Output:输出:
[ 'test2', 'test3' ]
This works fine when I have multiple values, but when only one parameter is sent, it creates a string instead of an Array当我有多个值时,这很好用,但是当只发送一个参数时,它会创建一个字符串而不是一个数组
Request: localhost:8000?propertyName=test3
Generates the output: test3
instead of [test3]
请求: localhost:8000?propertyName=test3
生成输出: test3
而不是[test3]
My current approach is to use (as per https://stackoverflow.com/a/4775737/5236575 )我目前的方法是使用(根据https://stackoverflow.com/a/4775737/5236575 )
propertyName = [].concat(propertyName)
to ensure the value is an array.以确保该值是一个数组。
Is there a way to force Nest.js to parse the query parameters as a string array at all times as this is required in multiple places across controllers.有没有办法强制 Nest.js 始终将查询参数解析为字符串数组,因为这在控制器的多个位置都是必需的。
Note: ValdiationPipe: transform
is set to true
注意:ValdiationPipe: transform
设置为true
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
Off the top of my head, you could use @Transform
decorator from class-transformer
to achieve that.在我的脑海中,您可以使用class-transformer
@Transform
装饰器来实现这一点。 You could move the logic of transforming a single string parameter to array with help of that decorator.您可以在该装饰器的帮助下移动将单个字符串参数转换为数组的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.