How to validate the direct function call in nestjs? - javascript

I am trying to send a direct function call, and I set the DTO, but not work.
here is the code (Send is my DTO) in my controller:
#Post('/Send')
async SendE(body: Send) {
const mail = await this.messageProducer.SendMessage(body);
return mail;
}
I make a direct call to SendE function here:
#MessagePattern('Notification')
async readMessage(#Payload() message: any, #Ctx() context: KafkaContext) {
const messageString = JSON.stringify(context.getMessage().value);
const toJson = JSON.parse(messageString);
await this.SendE(toJson);
}
I want the "Send" DTO can validate the "toJson", but it does not work.
here is what my DTO looks like:
export class Send{
#IsString()
#ApiProperty({ required: true })
MessageID: string;
}
here is what the toJson looks like:
{
MessageID: 123
}
If I send a non-string MessageID, it can pass the DTO.
Please help

You have to enable validationPipe to enable DTO's, There are 2 approaches according to the docs of NestJS. The ValidationPipe is exported from #nestjs/common.
1. Globally in your main.ts:
// validate incoming requests
app.useGlobalPipes(
new ValidationPipe({
transform: true,
})
);
2. Per controller
#Post()
#UsePipes(new ValidationPipe({ transform: true }))
async create(#Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}

Related

ValidationPipe doesn't strip given object in Nestjs

I'm using Nestjs and Mongoose orm the problem is ValidationPipe doesn't delete invalid props from request and send given(raw) request to my service.
This is main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: { origin: '*' },
});
app.useGlobalPipes(new ValidationPipe(
{
transform: true,
whitelist: true,
}
))
await app.listen(3002);
}
bootstrap();
and this is update-category.dto
export class UpdateCategoryDto {
#IsDefined()
id:string
#IsDefined()
title: string;
#IsDefined()
url: string;
}
And finally this is category.service
async updateCategories(categories: [UpdateCategoryDto]){
for (let i = 0; i < categories.length ; i++) {
console.log("given categories",categories);
await this.categoryModel.updateOne([{ _id: categories[i].id }],categories[i]);
}
}
Here is my simple controller
#Controller('categories')
export class CategoryController {
constructor(private categoryService: CategoryService) {}
#Put()
editCategories( #Body() updateCategories: [UpdateCategoryDto]) {
return this.categoryService.updateCategories(updateCategories);
}
}
when "given categories" logs items, they have _id which frontend sent to api while I didn't whitelisted that props in my dto. why I'm receaving that prop?? I also tried `forbidNonWhitelisted' and interestingly request didn't fail :)) seems useGlobalPipes doesn't work for me
Just use ParseArrayPipe.
Update your controller.ts:
#Put()
editCategories(#Body(new ParseArrayPipe({ items: UpdateCategoryDto, whitelist: true })) updateCategories: UpdateCategoryDto[]) {
return this.categoryService.updateCategories(updateCategories);
}
Ensure to have items and whitelist set.

NestJS: How to access both Body and Param in custom validator?

I've a scenario where I need values from both values in the param and body to perform custom validation. For example, I've a route /:photoId/tag that adds a tag to a photo.
However, before it can add a tag to a photo, it has to validate whether there is already an existing tag of the same name with the photo.
I have the following route in my controller:
#Post(':photoId/tag')
#UsePipes(new ValidationPipe())
async addTag(
#Param() params: AddTagParams,
#Body() addTagDto: AddTagDto
) {
// ...
}
Since the :photoId is provided as a param and the tag is provided in the body of the request, they can't access each other in the custom validator and I can't use both pieces of information to do a check against the database:
export class IsPhotoTagExistValidator implements ValidatorConstraintInterface {
async validate(val: any, args: ValidationArguments) {
// supposed to check whether a tag of the same name already exists on photo
// val only has the value of photoId but not the name of the tag from AddTagDto in Body
}
}
export class AddTagParams{
#IsInt()
#Validate(IsPhotoTagExistValidator) // this doesn't work because IsPhotoTagExistValidator can't access tag in AddTagDto
photoId: number
}
export class AddTagDto{
#IsString()
tag: string
}
As in the example above, the val in IsPhotoTagExistValidator is only the photoId. But I need both the photoId in Param and tag name in the Body to check whether the particular photoId already has that tag.
How should I access both the Body and Param in the custom validator function? If not, how should I approach this problem?
The only solution I have found so far was derived from this comment https://github.com/nestjs/nest/issues/528#issuecomment-497020970
context.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '#nestjs/common'
import { Observable } from 'rxjs'
/**
* Injects request data into the context, so that the ValidationPipe can use it.
*/
#Injectable()
export class ContextInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
next: CallHandler
): Observable<any> {
const request = context.switchToHttp().getRequest();
request.body.context = {
params: request.params,
query: request.query,
user: request.user,
};
return next.handle()
}
}
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new ContextInterceptor());
// ...
}
If you use {whitelist: true} in ValidationPipe params you will need to allow context in your Dto objects.
this can be done by extending such Dto:
context-aware.dto.ts
import { Allow } from 'class-validator';
export class ContextAwareDto {
#Allow()
context?: {
params: any,
query: any,
user: any,
}
}
After this, you will be able to access request data when validating body in custom validator via validationArguments.object.context
You can easily adjust the above to access the context when validating params or query, although I find it sufficient to have this only during body validation.

How to use validation in NestJs with HTML rendering?

NestJS uses validation with validation pipes and
#UsePipes(ValidationPipe)
If this fails it throws an exception. This is fine for REST APIs that return JSON.
How would one validate parameters when using HTML rendering and return
{ errors: ['First error'] }
to an hbs template?
You can create an Interceptor that transforms the validation error into an error response:
#Injectable()
export class ErrorsInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
call$: Observable<any>,
): Observable<any> {
return call$.pipe(
// Here you can map (or rethrow) errors
catchError(err => ({errors: [err.message]}),
),
);
}
}
You can use it by adding #UseInterceptors(ErrorsInterceptor) to your controller or its methods.
I've been driving myself half mad trying to find a "Nest like" way to do this while still retaining a degree of customisability, and I think I finally have it. Firstly, we want an error that has a reference to the exisiting class-validator errors, so we create a custom error class like so:
import { ValidationError } from 'class-validator';
export class ValidationFailedError extends Error {
validationErrors: ValidationError[];
target: any;
constructor(validationErrors) {
super();
this.validationErrors = validationErrors;
this.target = validationErrors[0].target
}
}
(We also have a reference to the class we tried to validate, so we can return our object as appropriate)
Then, in main.ts, we can set a custom exception factory like so:
app.useGlobalPipes(
new ValidationPipe({
exceptionFactory: (validationErrors: ValidationError[] = []) => {
return new ValidationFailedError(validationErrors);
},
}),
);
Next, we create an ExceptionFilter to catch our custom error like so:
#Catch(ValidationFailedError)
export class ValidationExceptionFilter implements ExceptionFilter {
view: string
objectName: string
constructor(view: string, objectName: string) {
this.view = view;
this.objectName = objectName;
}
async catch(exception: ValidationFailedError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
response.render(this.view, {
errors: exception.validationErrors,
[this.objectName]: exception.target,
url: request.url,
});
}
}
We also add an initializer, so we can specify what view to render and what the object's name is, so we can set up our filter on a controller method like so:
#Post(':postID')
#UseFilters(new ValidationExceptionFilter('blog-posts/edit', 'blogPost'))
#Redirect('/blog-posts', 301)
async update(
#Param('id') postID: string,
#Body() editBlogPostDto: EditBlogPostDto,
) {
await this.blogPostsService.update(postID, editBlogPostDto);
}
Hope this helps some folks, because I like NestJS, but it does seem like the docuemntation and tutorials are much more set up for JSON APIs than for more traditional full stack CRUD apps.

How to use query parameters in Nest.js?

I am a freshman in Nest.js.
And my code as below
#Get('findByFilter/:params')
async findByFilter(#Query() query): Promise<Article[]> {
}
I have used postman to test this router
http://localhost:3000/article/findByFilter/bug?google=1&baidu=2
Actually, I can get the query result { google: '1', baidu: '2' }. But I'm not clear why the url has a string 'bug'?
If I delete that word just like
http://localhost:3000/article/findByFilter?google=1&baidu=2
then the postman will shows statusCode 404.
Actually, I don't need the word bug, how to custom the router to realize my destination just like http://localhost:3000/article/findByFilter?google=1&baidu=2
Here's another question is how to make mutiple router point to one method?
Query parameters
You have to remove :params for it to work as expected:
#Get('findByFilter')
async findByFilter(#Query() query): Promise<Article[]> {
// ...
}
Path parameters
The :param syntax is for path parameters and matches any string on a path:
#Get('products/:id')
getProduct(#Param('id') id) {
matches the routes
localhost:3000/products/1
localhost:3000/products/2abc
// ...
Route wildcards
To match multiple endpoints to the same method you can use route wildcards:
#Get('other|te*st')
will match
localhost:3000/other
localhost:3000/test
localhost:3000/te123st
// ...
If you have you parameter as part or url: /articles/${articleId}/details, you wold use #Param
#Get('/articles/:ARTICLE_ID/details')
async getDetails(
#Param('ARTICLE_ID') articleId: string
)
IF you want to provide query params /article/findByFilter/bug?google=1&baidu=2, you could use
#Get('/article/findByFilter/bug?')
async find(
#Query('google') google: number,
#Query('baidu') baidu: number,
)
We can use #Req()
import { Controller, Get, Req } from '#nestjs/common';
import { Request } from 'express';
(...)
#Get(':framework')
getData(#Req() request: Request): Object {
return {...request.params, ...request.query};
}
/nest?version=7
{
"framework": "nest",
"version": "7"
}
read more
You can use the #Req decorator, and use param object, see :
#Get()
findAll(
#Req() req: Request
): Promise<any[]> {
console.log(req.query);
// another code ....
}
For better explaining I wrote a pagination example with number transformer class:
class QueryDto {
#Type(() => Number)
#IsInt()
public readonly page: number;
#Type(() => Number)
#IsInt()
public readonly take: number;
}
#Injectable()
class QueryTransformPipe implements PipeTransform {
async transform(value: QueryRequestDto, { metatype }: ArgumentMetadata) {
if (!metatype) {
return value;
}
return plainToInstance(metatype, value);
}
}
#Controller()
class YourController {
#Get()
// also you can use it with pipe decorator
// #UsePipes(new QueryTransformPipe())
public async getData(#Query(new QueryTransformPipe()) query?: QueryRequestDto): Promise<any[]> {
// here you get instanceof QueryTransformPipe
// and typeof query.page === 'number' && typeof query.take === 'number'
}
}

How to make param required in NestJS?

I would like to make my route Query parameter required.
If it is missing I expect it to throw 404 HTTP error.
#Controller('')
export class AppController {
constructor() {}
#Get('/businessdata/messages')
public async getAllMessages(
#Query('startDate', ValidateDate) startDate: string,
#Query('endDate', ValidateDate) endDate: string,
): Promise<string> {
...
}
}
I'm using NestJs pipes to determine if a parameter is valid, but not if it exists And I'm not sure that Pipes are made for that.
So how can I check in NestJS if my param exists if not throw an error?
Use class-validator. Pipes are definitely made for that !
Example :
create-user.dto.ts
import { IsNotEmpty } from 'class-validator';
export class CreateUserDto {
#IsNotEmpty()
password: string;
}
For more information see class-validator documentation :
https://github.com/typestack/class-validator
And NestJS Pipes & Validation documentation :
https://docs.nestjs.com/pipes
https://docs.nestjs.com/techniques/validation
NestJS does not provide a decorator (like #Query) that detects undefined
value in request.query[key].
You can write custom decorator for that:
import { createParamDecorator, ExecutionContext, BadRequestException } from '#nestjs/common'
export const QueryRequired = createParamDecorator(
(key: string, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest()
const value = request.query[key]
if (value === undefined) {
throw new BadRequestException(`Missing required query param: '${key}'`)
}
return value
}
)
Then use #QueryRequired decorator as you would use #Query:
#Get()
async someMethod(#QueryRequired('requiredParam') requiredParam: string): Promise<any> {
...
}
There hava a easy way to valide you parameter, https://docs.nestjs.com/techniques/validation
In addition to Phi's answer, you can combine the use of class-validator with the following global validation pipe:
app.useGlobalPipes(
new ValidationPipe({
/*
If set to true, instead of stripping non-whitelisted
properties validator will throw an exception.
*/
forbidNonWhitelisted: true,
/*
If set to true, validator will strip validated (returned)
object of any properties that do not use any validation decorators.
*/
whitelist: true,
}),
);
I use this in order to only allow parameters defined in the DTO class so that it will throw an error when unknown parameters are sent with the request!
In Phie's example, a post request with a body like {password: 'mypassword'} will pass the validation when {password: 'mypassword', other: 'reject me!'} won't.

Categories