Pipes
The most common pipe used with and provided by Nest.js is the ValidationPipe. This pipe, however, cannot be used with microservice handlers because it throws exceptions extending HttpException. All exceptions thrown in a microservice must extend RpcException. To fix this, we can extend the ValidationPipe, catch the HttpException, and throw an RpcException.
@
Injectable
()
export
class
RpcValidationPipe
extends
ValidationPipe
implements
PipeTransform
<
any
>
{
public
async
transform
(
value
:any
,
metadata
:ArgumentMetadata
)
{
try
{
await
super
.
transform
(
value
,
metadata
);
}
catch
(
error
)
{
if
(
error
instanceof
BadRequestException
)
{
throw
new
RpcValidationException
();
}
throw
error
;
}
return
value
;
}
}
Before we can use the ValidationPipe, we have to create a class that describes the format of the data our microservice method expects.
class
CreateUserRequest
{
@
IsEmail...