如何在nest.js中创建装饰器?

时间:2018-02-16 08:58:41

标签: typescript decorator nestjs

我有这么一段时间遇到麻烦了。我的装饰者应该为检查字段提供唯一值的信息。它看起来像这样:

ngbDatePicker

我的验证看起来像这样:

    <form class="form">
    <div class="row ml-5 mr-5 mb-2" *ngFor="let dataRow of data1; let in=index;">
        <div class="col-12 col-sm mb-2 mb-sm-0">
            <input class="form-control form-control-sm" #inpValue value="{{dataRow.fldValue}}" />
        </div>
        <div class="col-12 col-sm mb-2 mb-sm-0">
            <div class="input-group">
                <input class="form-control form-control-sm" placeholder="Start Date" name="ds"
                        [(ngModel)]="data1[in].inputStartDate" ngbDatepicker #ds="ngbDatepicker"/>
                <button class="input-group-addon" (click)="ds.toggle()" type="button">
                    <img src="assets/img/calendar_icon.gif" style="width: 1.2rem; height: 1rem; cursor: pointer;" />
                </button>
            </div>
        </div>
        <div class="col-12 col-sm mb-2 mb-sm-0">
            <div class="input-group">
                <input class="form-control form-control-sm" placeholder="End Date" name="de"
                        [(ngModel)]="data1[in].inputEndDate" ngbDatepicker #de="ngbDatepicker" />
                <button class="input-group-addon" (click)="de.toggle()" type="button">
                    <img src="assets/img/calendar_icon.gif" style="width: 1.2rem; height: 1rem; cursor: pointer;" />
                </button>
            </div>
        </div>
        <div class="col-12 col-sm mb-2 mb-sm-0">
            <button class="btn btn-primary btn-block w-100" (click)="saveBtn(dataRow, inpValue.value, dataRow.fldRowID)">Save</button>
        </div>
    </div>
</form>

执行代码后,看起来像md = undefined。那我怎么能检索我的元数据?也许,我以错误的方式使用createPropertyDecorator?

编辑: 经过几个小时后,我意识到nestjs没有“createPropertyDecorator”,我从swagger模块导入它(BIG错误)。所以我需要创建自己的功能。现在我这样做:

export const IsUnique = (
  metadata: {
    entity: any,
    field: string,
  },
): PropertyDecorator => {
  return createPropertyDecorator(constants.custom_decorators.is_unique, metadata);
};

所以,我的问题是一样的 - 如何正确定义元数据,所以它永远不会干扰其他人?

1 个答案:

答案 0 :(得分:1)

我使用不同的方法,我使用类验证器

export class SignInUser {
    @IsEmail()
    email: string;

    @Length(6, 50)
    password: string;
}

并在控制器中

signIn(@Body(new ValidationPipe()) signIn: SignInUser) {}

它就像一个魅力

NOTE: I use ValidationPipe from @nestjs/common

您可以为类验证器

创建自己的装饰器

https://github.com/typestack/class-validator#custom-validation-decorators