【问题标题】:how can I use decorator for method variable inside class in nestjs?如何在nestjs的类中使用装饰器作为方法变量?
【发布时间】:2022-09-29 17:38:42
【问题描述】:
import {isNotEmpty} from \"class-validator\";

export Service   {

create(createdto)
{
const {name,age} = createdto;

@isNotEmpty()
name          //using decorator to check whether name is null or 
undefined
} 
}

因为装饰器只对类方法有用,所以我不能在方法变量中使用它。 它如何验证方法变量?

  • 在此处了解装饰器:typescriptlang.org/docs/handbook/decorators.html 这与 nestjs 无关
  • 我不确定你在这里问什么。你绝对可以拥有属性装饰器。这就是class-validator 的基础
  • 请修复文本中的问题。
  • 感谢清理..我现在已将装饰器放入服务类方法中以验证其方法成员
  • 你想在哪里打电话validate

标签: javascript typescript nestjs decorator


【解决方案1】:

考虑到语言(ECMAScript2016/Typescript)不支持局部变量上的装饰器,您不能按照问题中描述的方式在服务中使用装饰器。

尽管如此,class-validator 还是为其验证功能提供了非装饰器实现。

在 class-validator 的 Github 上:https://github.com/typestack/class-validator#manual-validation 是这样写的:

Validator 中有几种方法允许执行基于非装饰器的验证:

import { isEmpty, isBoolean } from 'class-validator';

isEmpty(value); isBoolean(value);

因此,您可以使用如下代码实现相同的目标:

import { Injectable } from "@nestjs/common";
import { CreateDto } from "./dto/create.dto";
import { isEmpty, isInt } from "class-validator";

@Injectable()
export class TestValidationService {
  test(createDto: CreateDto) {
    const {name, age} = createDto;
    
    if (isEmpty(name)) {
      throw "There is no name.";
    }
    
    if (!isInt(age)) {
      throw "Age is not int."
    }
    
    return createDto;
  }
}

最后,如果在服务中使用一对一的方法不适合您,您仍然可以装饰您的 DTO,并使用类验证器中的 validate 方法。

像这样:

import { IsInt, IsNotEmpty } from "class-validator";

export class CreateDto {
  @IsNotEmpty()
  name: string;
  
  @IsInt()
  age: number
}

在您的服务中:

async testWithValidate(createDto: CreateDto) {
    const validationResult = await validate(createDto);
}

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 2014-02-18
    • 2016-10-14
    • 1970-01-01
    • 2020-12-04
    • 2017-07-28
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多