NestJS access response object in pipes

Viewed 3247

I am using pipes for request validation. If the request fails, I want to redirect to a page but don't want to throw error. The question is, how can I access the response object in validation?

This is my validation pipe.

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  async transform(value: any, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
     // in here i need to response with res.redirect('') function
      throw new BadRequestException('Validation failed');
    }
    return value;
  }
  private toValidate(metatype: Function): boolean {
    const types: Function[] = [String, Boolean, Number, Array, Object];
    return !types.includes(metatype);
  }
}

Instead of throwing exception i need to access res.redirect() function

1 Answers

The response object is not available from within the context of a pipe. What you could do is A) use an interceptor instead or B) throw an exception and use a filter to catch this specific exception and redirect to the correct location.

Pipes are only used for validation or object transformation and as such immediately return successes (with the possibly transformed object) or throw errors about why the transformation/validation failed.

Related