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.

Can't resolve dependency of component (validator constraint)

See original GitHub issue

Hi, I’ve got a problem. I’m using class-validator and creating my custom constraint like this:

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

  constructor(
    @Inject(UserRepositoryToken)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  validate(userInfo: any, args: ValidationArguments) {
    return this.userRepository.findOne(userInfo).then(user => !!user);
  }
}

export const IsTaken = (validationOptions?: ValidationOptions) => (
  (object: object, propertyName: string) => {
    registerDecorator({
      propertyName,
      target: object.constructor,
      options: validationOptions,
      constraints: [],
      validator: IsTakenConstraint,
    });
  }
);

Then IsTaken is used as decorator in user.dto.ts file and validation takes place in Pipe. But… I’m getting an error ‘Cannot read property ‘findOne’ of undefined’ so it seems like userRepository is not being injected into constructor. But it is exported from DatabaseModule and works properly in UsersService.

There is UsersModule:

@Module({
    modules: [DatabaseModule],
    controllers: [UsersController],
    components: [
        ...userProviders,
        IsTakenConstraint,
        UsersService,
    ],
})
export class UsersModule {}

And usersProviders:

export const userProviders = [
  {
    provide: UserRepositoryToken,
    useFactory: (connection: Connection) => connection.getRepository(UserEntity),
    inject: [DbConnectionToken],
  },
];

I’m sure I’m missing something important here…

Issue Analytics

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

github_iconTop GitHub Comments

2reactions
kamilmysliwieccommented, Oct 2, 2017

@Pesiok no issues, you can inject dependencies to both interceptors & guards, just remember to use controller or method scope (@UseGuards()). The global ones can’t inject anything. and thanks!! 🎉

1reaction
grzegorz-bielskicommented, Oct 2, 2017

Ok, thanks once again. For future reference and people, like me for whom it was not immediately obvious:

Controller setup:

@Controller('route')
export class SassyController {
  constructor(
    private readonly thingsRepository: Repository<Things>,
  ) {}

  @Get()
  @UseGuards(SomeGuard)
  getThings() {
    return 'things';
  }
}

Guard setup:

@Guard()
export class SomeGuard implements CanActivate {
  constructor(
    @Inject(ThingsRepositoryToken)
    private readonly thingsRepository: Repository<Things>,
  ) {}

  public canActivate(request, context: ExecutionContext): boolean {
    if (this.thingsRepository.someMethod()) {
      return true;
    } else {
     return false;
   }
  }
}

Yes, it’s that easy.

Read more comments on GitHub >

github_iconTop Results From Across the Web

nestjs - Nest can't resolve dependencies of the Constraint ...
It's a circular file reference. Having your service use a type import ( import type { Dto } from './dto' ) should resolve...
Read more >
How to have a custom symfony validator constraint ... - SitePoint
I am trying to create a custom symfony form validator constraint. I created two class, one constraint and one validator and it works...
Read more >
How to resolve javax.validation cannot be resolved? - YouTube
Check this video to find out how to solve ? ... Your browser can't play this video. ... Check maven dependency to be...
Read more >
resolve | Apache Ivy™
The resolve task actually resolve dependencies described in an ivy file, ... constraint (expressed with the rev attribute in the dependency element) is...
Read more >
nest can't resolve dependencies of the cache_manager
Modifying CacheModule so provider and exports are part of register / registerAsync instead of the @Module({}); Using imports: [forwardRef(() => CacheModule)], ...
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