Created
March 7, 2021 00:27
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 []; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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