nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.07k stars 7.56k forks source link

how to use skipMissingProperties in pipe #519

Closed llk2yq closed 6 years ago

llk2yq commented 6 years ago

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[x] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

I hava an entity with class-validator and pipe, and it works well. But the validator will check the params always , it is unexpected. It may be like this: 'insert' will check all the params , and 'update' will check params which was post, and 'delete' will not check;

l have found something about this: skipMissingProperties: true ,and beforeInsert from typeorm, but i dont know when and where to use it ,could u please give me some help?

Environment


Nest version:4.6.6


For Tooling issues:
- Node version: 8.9.4  
- Platform: Windows 10 

Others:

kamilmysliwiec commented 6 years ago

Hi @YYQ8023, You can pass options object into ValidationPipe() constructor. 🙂

llk2yq commented 6 years ago

I am a novice,thx for your help , i will try it ! @kamilmysliwiec

llk2yq commented 6 years ago

I found i can not complete it... em....... here is my code , could you help me , how to add constructor.....

import { Pipe, PipeTransform, ArgumentMetadata,BadRequestException } from "@nestjs/common";
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';

@Pipe()
export class ValidationPipe implements PipeTransform<any>{
  // constructor 
  async transform(value, metadata: ArgumentMetadata) {
    const { metatype } = metadata;
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    console.log("obj:",object,"metadata:",metadata);
    // {skipMissingProperties:true}
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new BadRequestException('validate fail');
    }
    return value;
  }
  private toValidate(metatype): boolean {
    const types = [String, Boolean, Number, Array, Object];
    return !types.find((type) => metatype === type);
  }
}
ghost commented 6 years ago

For referencing, here is the one of the available code for skipMissingProperties:

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  skip: boolean = false
  constructor(skip: boolean = false) { this.skip = skip; }
  async transform(value, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object, { skipMissingProperties: this.skip });
    console.log(errors);
    if (errors.length > 0) {
      throw new BadRequestException('Invalid Credentials');
    }
    return value;
  }

  private toValidate(metatype): boolean {
    const types = [String, Boolean, Number, Array, Object];
    return !types.find((type) => metatype === type);
  }
}
kamilmysliwiec commented 6 years ago

@YYQ8023 @YYQ8023 why not to use a built-in ValidationPipe as mentioned in the docs?

@UsePipes(new ValidationPipe({ skipMissingProperties: false }))
carmonac commented 5 years ago
@Post(':id')
@ApiOperation({
    title: 'Update data of an admin',
    description: 'Post method to edit details about a specific admin',
})
@Authorize(Roles.Admin)
@UsePipes(new ValidationPipe({ skipMissingProperties: true }))
async updateOne(@Param('id') id: string, @Body() admin: UpdateAdminDto) {
    const adminUpdated: IAdmin = await this.adminService.update(id, admin);
    return GenericResponse.Result(null, { adminUpdated });
}

@kamilmysliwiec doing what you propose, it continues validating all properties and I get Bad Request error.

jakobrosenberg commented 5 years ago

I get the exact same error as @careuno. Example from nestjsx/crud below.

  @UsePipes(new ValidationPipe({ skipMissingProperties: true }))
  @Override()
  async updateOne(@Param() params, @Body() body: editEntryDto) {
    const item = <menu_entry>body;
    return await this.service.repo.update(id, item);
  }

propA must be a string, propB must be a string. etc...

lock[bot] commented 5 years ago

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.