Reputation: 31
I am working on a project which is based on the nest.js framework
The following is a snippet of my function:
@Post('beneficiaries/:beneficiaryId/bankDetails')
@HttpCode(HttpStatus.OK)
async addBankDetails(@Param('beneficiaryId', new ValidationPipe()) beneficiaryHash: BeneficiaryHashIdDto, @Body() body, @Headers() headers) {
const beneficiary = await this.beneficiaryService.getBeneficiaryIdFromHash(beneficiaryHash, ['beneficiaryId', 'currencyCode', 'countryCode']);
let routingOptions = await this.beneficiaryService.getBeneficiaryRoutingConfig(beneficiary.beneficiaryId, pick(headers, GET_HEADERS_LIST));
routingOptions = lmap(routingOptions, partialRight(pick, ['bankDetail', 'beneficiaryRoutingConfigId']));
const [routingConfig] = routingOptions.filter(item => item.beneficiaryRoutingConfigId === body.beneficiaryRoutingConfigId);
if (!routingConfig) {
throw new BadRequestException('Invalid beneficiaryRoutingConfigId');
}
const { error } = this.beneficiaryService.bankDetailsSchema(routingConfig.bankDetail).validate(body, { abortEarly: false });
if (error) {
throw new BadRequestException(error);
}
// write here logic to validate routing codes
await this.beneficiaryService.validateBeneficiaryBankDetails(routingConfig, body, pick(headers, GET_HEADERS_LIST), beneficiary);
// write here logic to insert bank details of bene
return this.beneficiaryService.updateBankDetails(body, headers, beneficiary.beneficiaryId);
}
Nest allows us to extract the params, headers, body, etc of a request.
https://docs.nestjs.com/controllers
I want to extract a particular key from my params
For example my params contain: 1.clientId 2.customerId 3.beneficiaryId
I am able to take out the beneficiaryId and store it in beneficiaryHash but I am not able to perform a validation at the same time.Is there any work around?
Upvotes: 0
Views: 51
Reputation: 884
You can reach it by custom pipes. as a example like ParseIntPipe
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
@Injectable()
export class ParseIntPipe implements PipeTransform<string, number> {
transform(value: string, metadata: ArgumentMetadata): number {
const val = parseInt(value, 10);
if (isNaN(val)) {
throw new BadRequestException('Validation failed');
}
return val;
}
}
@Get(':id')
async findOne(@Param('id', new ParseIntPipe()) id) {
return this.catsService.findOne(id);
}
for more knowledge please read https://docs.nestjs.com/pipes#transformation-use-case
Upvotes: 1