Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DTO not working for microservice, but working for apis directly

I am developing apis & microservices in nestJS, this is my controller function

    @Post()
    @MessagePattern({ service: TRANSACTION_SERVICE, msg: 'create' })
    create( @Body() createTransactionDto: TransactionDto_create ) : Promise<Transaction>{
        return this.transactionsService.create(createTransactionDto)
    }

when i call post api, dto validation works fine, but when i call this using microservice validation does not work and it passes to service without rejecting with error. here is my DTO

import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class TransactionDto_create{
    @IsNotEmpty()
    action: string;

    // @IsString()
    readonly rec_id : string;

    @IsNotEmpty()
    readonly data : Object;

    extras : Object;
    // readonly extras2 : Object;
}

when i call api without action parameter it shows error action required but when i call this from microservice using

const pattern = { service: TRANSACTION_SERVICE, msg: 'create' }; const data = {id: '5d1de5d787db5151903c80b9', extras:{'asdf':'dsf'}};

return this.client.send<number>(pattern, data)

it does not throw error and goes to service. I have added globalpipe validation also.

app.useGlobalPipes(new ValidationPipe({
    disableErrorMessages: false,  // set true to hide detailed error message
    whitelist: false,  // set true to strip params which are not in DTO
    transform: false // set true if you want DTO to convert params to DTO class by default its false
  }));

how will it work for both api & microservice, because i need all at one place and with same functionality so that as per clients it can be called.

like image 699
Muhammad Aadil Banaras Avatar asked Oct 29 '25 03:10

Muhammad Aadil Banaras


1 Answers

ValidationPipe throws HTTP BadRequestException, where as the proxy client expects RpcException.

@Catch(HttpException)
export class RpcValidationFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        return new RpcException(exception.getResponse())
    }
}
@UseFilters(new RpcValidationFilter())
@MessagePattern('validate')
async validate(
    @Payload(new ValidationPipe({ whitelist: true })) payload: SomeDTO,
) {
    // payload validates to SomeDto 
    . . .
}
like image 162
hardyRocks Avatar answered Oct 31 '25 22:10

hardyRocks