import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, } from "class-validator"; import { CountriesService } from "../../countries/countries.service"; import { Country } from "../../countries/country.model"; import { State } from "../../countries/states.model"; import { Injectable } from "@nestjs/common"; @Injectable() @ValidatorConstraint({ async: true }) export class ProvinceExistsInCountryConstraints implements ValidatorConstraintInterface { constructor(private readonly countryService: CountriesService) {} validate(countryName: any, validationArguments: ValidationArguments): Promise | boolean { const [relatedPropertyName] = validationArguments.constraints; const relatedValue = (validationArguments?.object as any)[relatedPropertyName]; return this.countryService.getCountryByName(countryName).then(async (country: Country) => { const states: State[] = await this.countryService.getStates(country.getId()); return !!states.find((state: State) => state.getName() === relatedValue); }); } } export function DoesProvinceExistsInCountry(validationOptions?: ValidationOptions) { return function (object: Record, propertyName: string) { registerDecorator({ target: object.constructor, propertyName, options: validationOptions, constraints: [], validator: ProvinceExistsInCountryConstraints, }); }; }