import {
  ValidatorConstraint,
  ValidatorConstraintInterface,
  ValidationArguments,
  ValidationOptions,
  registerDecorator,
} from 'class-validator';

@ValidatorConstraint()
export class IsUniqueArray implements ValidatorConstraintInterface {
  validate(arr: any[]) {
    return arr.length === new Set(arr).size;
  }

  defaultMessage(args: ValidationArguments) {
    return `${args.property} should be an array of unique values`;
  }
}
/**
 * 配列内の値がすべてユニークであるかをチェックする
 * @param [validationOptions]
 * @returns
 */
export function IsUnique(validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      name: 'isUnique',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: validationOptions,
      validator: IsUniqueArray,
    });
  };
}
