Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't inject services which extend RepositoryService #36

Closed
kairauer opened this issue Mar 10, 2019 · 8 comments
Closed

Can't inject services which extend RepositoryService #36

kairauer opened this issue Mar 10, 2019 · 8 comments

Comments

@kairauer
Copy link

kairauer commented Mar 10, 2019

I tried to implement a custom validator with class-validator https://github.com/typestack/class-validator#custom-validation-classes. I used the example project from this repository.

I added the following class:

import { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
import { Injectable } from '@nestjs/common';
import { UsersService } from './users.service';

@ValidatorConstraint({ name: 'doesUserAlreadyExist', async: true })
@Injectable()
export class DoesUserAlreadyExist implements ValidatorConstraintInterface {
  constructor(private usersService: UsersService) {}

  async validate(text: string) {
    const users = await this.usersService.getMany({
        filter: [
            {
                field: 'email',
                operator: 'eq',
                value: text
            }
        ]
    });
    return users.length === 0 ? true : false;
  }
}

And added the validator to the User class (Entity):

...
  @Validate(DoesUserAlreadyExist, {
    message: 'User already exists',
  })
  @Column({ type: 'varchar', length: 255, nullable: false, unique: true })
  email: string;
...

I get the following error:

/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/@nestjs/typeorm/dist/common/typeorm.utils.js:8
    return `${entity.name}Repository`;
                     ^
TypeError: Cannot read property 'name' of undefined
    at Object.getRepositoryToken (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/@nestjs/typeorm/dist/common/typeorm.utils.js:8:22)
    at Object.exports.InjectRepository (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/@nestjs/typeorm/dist/common/typeorm.decorators.js:5:72)
    at Object.<anonymous> (/Users/kai/Development/NodeJS/crud/integration/typeorm/src/users/users.service.ts:12:16)
    at Module._compile (internal/modules/cjs/loader.js:738:30)
    at Module.m._compile (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/ts-node/src/index.ts:439:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:749:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:630:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
    at Function.Module._load (internal/modules/cjs/loader.js:562:3)

If I remove the injected UsersService dependency injection from the DoesUserAlreadyExist class everything works again.
Is it not possible to use the services which extends the RepositoryService service? Or is there another way to execute the repository methods (getMany, getOne, etc.)?

@michaelyali
Copy link
Member

Ok, could you please create a service as you normally do (not a RepositoryService, but just a dummy service) and inject it to your DoesUserAlreadyExist. And tell me if you still get this error. Thanks

@kairauer
Copy link
Author

kairauer commented Mar 11, 2019

I created the following Service:

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersTestService {
  constructor() {
    console.log('UsersTestService');
  }
}

added the service to the UsersModule provider and injected the service in the DoesUserAlreadyExist validator:

...
constructor(private usersTestService: UsersTestService) {}
...

Everything works fine with this dummy service. Is there another way to execute repository methods?

@michaelyali
Copy link
Member

michaelyali commented Mar 11, 2019

@kairauer
And if you inject TypeORM repository into your dummy service, would you be able to see that error in this case?

@kairauer
Copy link
Author

I changed the dummy service:

import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UsersTestService {
  constructor(private userRepository: Repository<User>) {
    console.log('UsersTestService', this.userRepository);
  }
}

Now I get an error again:

Error: Nest can't resolve dependencies of the UsersTestService (?). Please make sure that the argument at index [0] is available in the UsersModule context.
    at Injector.lookupComponentInExports (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/@nestjs/core/injector/injector.js:144:19)
    at processTicksAndRejections (internal/process/next_tick.js:81:5)
    at process.runNextTicks [as _tickCallback] (internal/process/next_tick.js:51:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:804:11)
    at Object.<anonymous> (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/ts-node/src/bin.ts:157:12)
    at Module._compile (internal/modules/cjs/loader.js:738:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
    at Module.load (internal/modules/cjs/loader.js:630:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
    at Function.Module._load (internal/modules/cjs/loader.js:562:3)

But I am pretty sure, that I injected a service (which injected the repository) in the past like its mentioned in the docs: https://docs.nestjs.com/recipes/sql-typeorm
Any ideas? And by the way, thanks for the fast response 👍

@michaelyali
Copy link
Member

Now you get another error, and it's not what I'm trying to get. We need to reproduce the first error.
So, as I can see, you're trying to inject repository in a wrong way. Please try this and tell me the result:

import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';

@Injectable()
export class UsersTestService {
  constructor(@InjectRepository(User) private userRepository: Repository<User>) {
    console.log('UsersTestService', this.userRepository);
  }
}

@kairauer
Copy link
Author

Yes, you are right, that wasn't the right way to inject the repository. I tried it with your solution, now I get nearly the same error as in my first post:

TypeError: Cannot read property 'name' of undefined
    at Object.getRepositoryToken (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/@nestjs/typeorm/dist/common/typeorm.utils.js:8:22)
    at Object.exports.InjectRepository (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/@nestjs/typeorm/dist/common/typeorm.decorators.js:5:72)
    at Object.<anonymous> (/Users/kai/Development/NodeJS/crud/integration/typeorm/src/users/test.service.ts:8:16)
    at Module._compile (internal/modules/cjs/loader.js:738:30)
    at Module.m._compile (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/ts-node/src/index.ts:439:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:749:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/kai/Development/NodeJS/crud/integration/typeorm/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:630:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
    at Function.Module._load (internal/modules/cjs/loader.js:562:3)

So, it seems like it's not caused by the extended RepositoryService class, right? I could fork the repo and implement the changes I did, if that helps to debug this.

@michaelyali
Copy link
Member

Yes, that was my point. And, in general, I think it has nothing to do with RepositoryService or with NestJs, but I think it's a TypeORM issue instead.

@kairauer
Copy link
Author

To anyone else who gets a similar issue, I think this is related to this issue: nestjs/nest#528

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants