modify delete comment
This commit is contained in:
@@ -6,6 +6,7 @@ import {
|
||||
ValidationOptions,
|
||||
registerDecorator,
|
||||
} from 'class-validator';
|
||||
import { isArray, isNil } from 'lodash';
|
||||
import { ObjectType, Repository, DataSource } from 'typeorm';
|
||||
|
||||
type Condition = {
|
||||
@@ -18,9 +19,11 @@ type Condition = {
|
||||
export class DataExistConstraint implements ValidatorConstraintInterface {
|
||||
constructor(private dataSource: DataSource) {}
|
||||
|
||||
errorValues: any[] = [];
|
||||
|
||||
async validate(value: any, validationArguments?: ValidationArguments) {
|
||||
let repo: Repository<any>;
|
||||
if (!value) {
|
||||
if (isNil(value)) {
|
||||
return true;
|
||||
}
|
||||
let map = 'id';
|
||||
@@ -30,6 +33,22 @@ export class DataExistConstraint implements ValidatorConstraintInterface {
|
||||
} else {
|
||||
repo = this.dataSource.getRepository(validationArguments.constraints[0]);
|
||||
}
|
||||
if (isArray(value)) {
|
||||
const values = value as any[];
|
||||
const validationResults = await Promise.all(
|
||||
values.map(async (val) => {
|
||||
if (isNil(val)) {
|
||||
return false;
|
||||
}
|
||||
const item = await repo.findOne({ where: { [map]: val } });
|
||||
if (isNil(item)) {
|
||||
this.errorValues.push(val);
|
||||
}
|
||||
return !isNil(item);
|
||||
}),
|
||||
);
|
||||
return validationResults.every((isValid) => isValid);
|
||||
}
|
||||
const item = await repo.findOne({ where: { [map]: value } });
|
||||
return !!item;
|
||||
}
|
||||
@@ -37,6 +56,11 @@ export class DataExistConstraint implements ValidatorConstraintInterface {
|
||||
if (!validationArguments.constraints[0]) {
|
||||
return 'Model not been specified!';
|
||||
}
|
||||
if (this.errorValues.length > 0) {
|
||||
return `All instance of ${
|
||||
validationArguments.constraints[0].name
|
||||
} must been exists in databse!Errors are ${this.errorValues.join(',')}`;
|
||||
}
|
||||
return `All instance of ${validationArguments.constraints[0].name} must been exists in databse!`;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user