It will be useful to validate headers along with all Body, Query etc. Is not always about keys and tokens so that you use a guard
, there can also be other values that you want to use in headers for some methods. Taking advantage of class-validator, transforms and DTO
that nestjs is promoting
@Headers("x-lang", LangPipe, CustomValidationPipe) langDto LangDto;
Thanks
Leaving it here in case someone needs it. As said by @kamilmysliwiec , a custom decorator can be used for validating the headers. (In the same way we validate req body ! )
import { createParamDecorator, ExecutionContext } from '@nestjs/commom'
import { plainToClass } from 'class-transformer';
import { ClassType } from 'class-transformer/ClassTransformer';
import { validateOrReject } from 'class-validator';
export const RequestHeader = createParamDecorator(
async (value: ClassType<unknown>, ctx: ExecutionContext) => {
// extract headers
const headers = ctx.switchToHttp().getRequest().headers;
// Convert headers to DTO object
const dto = plainToClass(value, headers, { excludeExtraneousValues: true });
// Validate
await validateOrReject(dto);
// return header dto object
return dto;
},
);
Define your header dto according to the headers which would be coming
import { IsDefined, IsString } from "class-validator";
export class HeaderDTO {
@IsString()
@IsDefined()
@Expose({ name: 'myheader1' }) // required as headers are case insensitive
myHeader1: string;
@IsString()
@IsDefined()
@Expose({ name: 'myheader1' })
myHeader2: string;
}
Finally use it as a method param and pass the dto you want to validate against :)
@Get('/hello')
getHello(@RequestHeader(HeaderDTO) headers: any) {
console.log(headers);
}
}
Most helpful comment
Leaving it here in case someone needs it. As said by @kamilmysliwiec , a custom decorator can be used for validating the headers. (In the same way we validate req body ! )
request-header.decorator.ts
Define your header dto according to the headers which would be coming
header.dto.ts
Finally use it as a method param and pass the dto you want to validate against :)