我很长一段时间都遇到了麻烦。我的装饰器应该提供信息以检查字段的唯一值。它看起来像这样:
export const IsUnique = (
metadata: {
entity: any,
field: string,
},
): PropertyDecorator => {
return createPropertyDecorator(constants.custom_decorators.is_unique, metadata);
};
我的验证看起来像这样:
import { HttpException } from '@nestjs/common';
import { PipeTransform, Pipe, ArgumentMetadata, HttpStatus } from '@nestjs/common';
import {validate, ValidationError} from 'class-validator';
import { plainToClass } from 'class-transformer';
import constants from '../../../constants';
@Pipe()
export class ValidationPipe implements PipeTransform<any> {
async transform(value, metadata: ArgumentMetadata) {
console.log(arguments);
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
const myErrors = await this.uniqueValidation(object);
if (errors.length > 0) {
throw new HttpException(errors, HttpStatus.BAD_REQUEST);
}
return value;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find((type) => metatype === type);
}
private async uniqueValidation(object): Promise<ValidationError[]|null>{
const md = Reflect.getMetadata('swagger/apiModelPropertiesArray', object);
console.log(md);
return null;
}
}
执行代码后,看起来像 md=undefined。那么我如何检索我的元数据呢?也许,我以错误的方式使用 createPropertyDecorator?
编辑:几个小时后,我意识到nestjs没有“createPropertyDecorator”,我从swagger模块导入它(大错误)。所以我需要创建自己的功能。现在我这样做:
export const IsUnique = (
metadata: {
entity: any,
field: string,
},
): PropertyDecorator => {
return (target: object, propertyKey: string) => {
const args = Reflect.getMetadata(constants.custom_decorators.is_unique, target, propertyKey) || {};
const modifiedArgs = Object.assign(args, { IsUnique: metadata.field });
Reflect.defineMetadata(constants.custom_decorators.is_unique, modifiedArgs, target);
};
};
所以,我的问题是一样的——如何正确定义元数据,这样它就不会干扰其他人的?