使用装饰器修改DTO属性

时间:2020-03-04 05:50:14

标签: node.js nestjs

export class MyDto extends Base{
@ApiModelProperty()
@Expose()
@MyCustomModifier()
readonly code: string = "";



MyCustomModifier(){
   // modify 
    code = someUpdateOnCode()
}

我们可以这样做吗,所以我们可以更新dto属性

1 个答案:

答案 0 :(得分:0)

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(private readonly schema) {}

  transform(value: any, metadata: ArgumentMetadata) {
    const { error } = this.schema.validate(value);
    if (error) {
      console.log(error, 'error');
      throw new BadRequestException(error.message);
    }
    // some changing value.code = someUpdateOnCode()
    return value;
  }
}

并像这样使用您的管道

import * as Joi from '@hapi/joi';
@Put('')
@UsePipes(
    new JoiValidationPipe(
        Joi.object().keys({
            code: Joi.string()
                .min(3)
                .max(250)
                .allow('')
                .optional()
        )
    })
  async someControler(){}