question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Question] Pb with custom repository in class-validator custom

See original GitHub issue

Hi !

Little problème when i add Custom validator to an Entity :

@ValidatorConstraint({ async: true })
export class IsProductNotExistConstraint implements ValidatorConstraintInterface {

  public validate = async (productName: any, _args: ValidationArguments): Promise<boolean> => {
    const product: Product | undefined = await RepositoryFactory.getRepository(ProductRepository).findOneByName(productName);
    if (product === undefined) {
      return false;
    } else {
      return true;
    }
  }

}

export function IsProductNotExist(validationOptions?: ValidationOptions): ((object: Object, propertyName: string) => void) {
  return (object: Object, propertyName: string): void => {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsProductNotExistConstraint
    });
  };
}

The factory use connection.getCustomRepository function. But if i do this, routing-controller return this response :

{ "name": "CustomRepositoryCannotInheritRepositoryError", "message": "Custom entity repository ProductRepository cannot inherit Repository class without entity being set in the @EntityRepository decorator." }

Alright, my repository use EntityRepository decorator :

@EntityRepository(Product)
export class ProductRepository extends Repository<Product> {

  public findOneByName = async (name: string): Promise<Product | undefined> => {
    return this.findOne({name: name});
  }

}

Have an idea to fix this ? Thanks ! And great job !

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
pleerockcommented, Nov 30, 2017

Try to add console.log before entityrepository decorator:

console.log("Product", Product);
@EntityRepository(Product)

And you’ll see Product undefined in console.

How this can be possible? It executes Product entity code after it executes this code because someone else is executing something else that has dependency in product and somewhere else, hard to say, you have a bad files organization and circular references which cannot be resolved by language. I suggest you to start from scratch and organize a better project structure.

This issue not related to typeorm somehow so Im closing it.

0reactions
StephenBegcommented, Nov 30, 2017

Hi,

Thanks for answer. I see the circular reference : Entity -> Validator -> Custom Repository -> Entity -> …

I thinks this pb is unsolvabled and your example in class-validator project doesn’t work to :

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

@ValidatorConstraint({ async: true })
export class IsUserAlreadyExistConstraint implements ValidatorConstraintInterface {

    validate(userName: any, args: ValidationArguments) {
        return UserRepository.findOneByName(userName).then(user => {
            if (user) return false;
            return true;
        });
    }

}

export function IsUserAlreadyExist(validationOptions?: ValidationOptions) {
   return function (object: Object, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            constraints: [],
            validator: IsUserAlreadyExistConstraint
        });
   };
}

(UserRepository) create a circular reference.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Spring Boot with Validation - Inject repository inside custom ...
Problem : When I test the endpoint, I have a NullPointerException . At first, during MVC validation the repository is correctly injected. But ......
Read more >
Custom validation with database in NestJS
Now you can use your custom validation constraint. Simply decorate class property with @Validate(UserExistsRule) decorator:.
Read more >
typestack/class-validator - Gitter
I'm trying to validate an array of UUIDv2, I know there is one for a single attribute. Can I do this somehow without...
Read more >
Spring Custom Validator by example - Dev in Web
See an example of custom validation annotation in Spring. Follow step-by-step tutorial on how to build a constraint annotation and a custom ......
Read more >
Validation with Spring Boot - the Complete Guide - Reflectoring
Spring Boot's Bean Validation support comes with the validation starter, ... later in the tutorial, when we're building a custom validator).
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found