[英]Access multipe parameters with a custom pipe in Nest.js
I'm trying to write a custom validation pipe to validate a request with multiple parameters.我正在尝试编写自定义验证 pipe 来验证具有多个参数的请求。 And I want to validate one param with a custom pipe, but another param is also needed to be used in the validation, and I didn't find the way described in the document.
而我想用自定义的pipe验证一个参数,但是验证中还需要使用另一个参数,我没有找到文档中描述的方法。
For example, this is my API, it requires a chainId
and an address
as input parameters.例如,这是我的 API,它需要一个
chainId
和一个address
作为输入参数。 I need to validate that the address is valid, but I can't do this without chainId
.我需要验证地址是否有效,但没有
chainId
就无法执行此操作。
Here's my code, I wrote the pipe followed by the document about custom pipe examples :这是我的代码,我写了 pipe,然后是关于自定义 pipe 示例的文档:
Controller Controller
@Put('/:chainId/tokens/:address')
@ApiOperation({
summary: 'Create a token',
})
async create(
@Param('chainId') chainId: number,
@Param('address', new AddressValidationPipe()) address: string,
): Promise<Token> {
return await this.tokensService.save(chainId, address);
}
Validation pipe验证 pipe
@Injectable()
export class AddressValidationPipe implements PipeTransform {
async transform(address: string) {
// chainId should be another param, but I don't know how to get it in this pipe
const chainId = 4;
if (!validator(chainId, address)) {
throw new BadRequestException(
'Address is not valid, or it is not on this chain',
);
}
return address;
}
}
After some research, I found that I can have these two params into this pipe in one time, and only validate the address.经过一番研究,我发现我可以一次性将这两个参数传入这个pipe,并且只验证地址。
Validation Pipe验证 Pipe
@Injectable()
export class AddressValidationPipe implements PipeTransform {
constructor(private readonly configService: ConfigService) {}
async transform(value: { chainId: string; address: string }) {
const { chainId, address } = value;
if (!validator(Number(chainId), address)) {
throw new BadRequestException(
'Address is not valid, or it is not on this chain',
);
}
return { chainId: Number(chainId), address };
}
}
Although in this way, I must convert the chainId
to number by myself, and I need to tell the swagger what params I'm using because I'm not writing them as each argument in my controller.虽然这样,我必须自己将
chainId
转换为数字,并且我需要告诉 swagger 我正在使用什么参数,因为我没有将它们写为我的 controller 中的每个参数。
Controller Controller
@ApiParam({
name: 'address',
description: 'Address of the token',
type: String,
})
@ApiParam({
name: 'chainId',
description: 'Chain ID of the token',
type: Number,
})
@Put('/:chainId/tokens/:address')
@ApiOperation({
summary: 'Create a token',
})
async create(
@Param(AddressValidationPipe) param: { chainId: number; address: string },
): Promise<Token> {
const { chainId, address } = param;
return await this.tokensService.save(chainId, address);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.