Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Edgar-P-yan/82cd19e48cbb2eacfa8cf81ec2a76c44 to your computer and use it in GitHub Desktop.
Save Edgar-P-yan/82cd19e48cbb2eacfa8cf81ec2a76c44 to your computer and use it in GitHub Desktop.
[Nest.js] Decorator for validating headers with ValidationPipe, class-validator and class-transformer
// get-books-headers.dto.ts
import { Contains } from 'class-validator';
class GetBooksHeadersDto {
@Contains('en')
'accept-language': string;
}
// books.controller.ts
import { HeadersWithValidation } from './headers-with-validation.decorator.ts'
import { GetBooksHeadersDto } from './get-books-headers.dto.ts';
@Controller()
class BooksController {
@Get()
getBooks (
@HeadersWithValidation(() => GetBooksHeadersDto) headers: GetBooksHeadersDto,
) {
console.log(headers['accept-language']); // contains 'en'
return [];
}
}
import { createParamDecorator, ExecutionContext, ValidationPipe } from '@nestjs/common';
import { ClassConstructor } from 'class-transformer';
/**
* Decorator for validating headers with ValidationPipe, class-transformer and class-validator.
*
* @example
* // require user agent to accept english
*
* class GetBooksHeadersDto {
* (a)Contains('en')
* 'accept-language': string
* }
*
* (a)Get()
* getBooks(
* (a)HeadersWithValidation(() => GetBooksHeadersDto) headers: GetBooksHeadersDto,
* ) {...}
*/
export const HeadersWithValidation = createParamDecorator(
async (typeResolver: () => ClassConstructor<unknown>, ctx: ExecutionContext) => {
// extract headers
const headers = ctx.switchToHttp().getRequest().headers;
const validationPipe = new ValidationPipe({
expectedType: typeResolver(),
transform: true,
whitelist: true,
validateCustomDecorators: true,
});
const result = await validationPipe.transform(headers, {
type: 'custom',
});
return result;
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment