Nest: [SUGGESTION] Let Headers decorators accepts pipes

Created on 1 Dec 2017  路  7Comments  路  Source: nestjs/nest

Cannot add pipes to headers decorator now.

It's very useful.

Most helpful comment

why can not i use @UsePipes(new JoiValidationPipe(schema)) and validate headers?, for example if is required token or need some format, to me is the same to params and body.

//JoiValidationPipe
import * as Joi from 'joi';
import * as expressJoi from 'express-joi-validator';
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException, Type } from '@nestjs/common';

export interface ArgumentMetadata2 {
  readonly type: 'body' | 'query' | 'param' | 'custom' | 'headers';
  readonly metatype?: Type<any>;
  readonly data?: string;
}

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(private readonly schema: object) {}

  transform(value: any, metadata: ArgumentMetadata2) {
    console.log(value, metadata, JSON.stringify(metadata.metatype));
    const { error } = Joi.validate(value, this.schema[metadata.type]);
    if (error) {
      throw new BadRequestException(`Validation failed in ${metadata.type}`, error.details[0].message);
    }
    return value;
  }
}

const schema = { query: { type: Joi.number(), }, body: { example: Joi.number().required(), }, param: { id: Joi.string().min(3).max(30).required(), }, headers: { 'x-token': Joi.string().required(), }, };

//controller
@Post('/create2/:id')
  @UsePipes(new JoiValidationPipe(schema))
  @Header('Cache-Control', 'none')
  create2(
    @Param() all,
    @Body() body,
    @Query() query,
    @Headers() headers): string {
    return `params: #${JSON.stringify(all)}.. body: #${JSON.stringify(body)} ... header: #${JSON.stringify(headers)}`;
  }

All 7 comments

Could You make an Example of what you need to achieve ?
so we could have a clear understanding of what you mean , It will be Helpful :smiley:

I want to use pipes in @Headers like down below.

    @Get()
    async getResources(
        @Query('type', new ValidatePipe()) type: Type,
        @Param('id', new ParseIntPipe()) id= 0,
        @Headers('token', new ParseTokenPipe()) token,
    ) {
        ...
    }

Hi @WangZishi,
Why not parse token inside middleware / interceptor / guard? If we would allow binding pipes to headers, the global pipes (for example ValidationPipe) would run for them as well. I think it's redundant.

why can not i use @UsePipes(new JoiValidationPipe(schema)) and validate headers?, for example if is required token or need some format, to me is the same to params and body.

//JoiValidationPipe
import * as Joi from 'joi';
import * as expressJoi from 'express-joi-validator';
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException, Type } from '@nestjs/common';

export interface ArgumentMetadata2 {
  readonly type: 'body' | 'query' | 'param' | 'custom' | 'headers';
  readonly metatype?: Type<any>;
  readonly data?: string;
}

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(private readonly schema: object) {}

  transform(value: any, metadata: ArgumentMetadata2) {
    console.log(value, metadata, JSON.stringify(metadata.metatype));
    const { error } = Joi.validate(value, this.schema[metadata.type]);
    if (error) {
      throw new BadRequestException(`Validation failed in ${metadata.type}`, error.details[0].message);
    }
    return value;
  }
}

const schema = { query: { type: Joi.number(), }, body: { example: Joi.number().required(), }, param: { id: Joi.string().min(3).max(30).required(), }, headers: { 'x-token': Joi.string().required(), }, };

//controller
@Post('/create2/:id')
  @UsePipes(new JoiValidationPipe(schema))
  @Header('Cache-Control', 'none')
  create2(
    @Param() all,
    @Body() body,
    @Query() query,
    @Headers() headers): string {
    return `params: #${JSON.stringify(all)}.. body: #${JSON.stringify(body)} ... header: #${JSON.stringify(headers)}`;
  }

I too feel that having validation pipe run over headers would be easier than creating additional interceptors or manual validation. We pass most our important values via headers and validating them would be easiest w/ @IsNotEmpty, etc.

Why is this issue closed? Validating my token which is coming from in the headers is a typical thing.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings