Nest: Upgrade To 5.0.0 Breaks Server Bootup - Nest can't resolve dependencies

Created on 22 May 2018  ·  16Comments  ·  Source: nestjs/nest

This potential bug crashes the Nestjs server on bootup and stops all development work on the front and back ends.

I'm submitting a...


[ ] Regression 
[x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Booting Nestjs with npm run start gives this message and the server won't boot:

[Nest] 24918   - 2018-5-22 18:44:51   [NestFactory] Starting Nest application...
[Nest] 24918   - 2018-5-22 18:44:52   [InstanceLoader] TypeOrmModule dependencies initialized +277ms
[Nest] 24918   - 2018-5-22 18:44:52   [ExceptionHandler] Nest can't resolve dependencies of the MembersService (?). Please verify whether [0] argument is available in the current context.
Error: Nest can't resolve dependencies of the MembersService (?). Please verify whether [0] argument is available in the current context.
    at Injector.lookupComponentInExports (/home/vagrant/nestjs/node_modules/@nestjs/core/injector/injector.js:129:19)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
    at Function.Module.runMain (module.js:695:11)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
 1: node::Abort() [node]
 2: 0x8c2459 [node]
 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [node]
 4: 0xad6f2c [node]
 5: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [node]
 6: 0x25713df842fd
Aborted (core dumped)
npm ERR! code ELIFECYCLE
npm ERR! errno 134
npm ERR! [email protected] start: `node index.js`
npm ERR! Exit status 134
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Expected behavior

After the minor modification to a service of replacing @Component with @Injectable the server should just boot up. The code worked with full CRUD before the upgrade to v5.

Minimal reproduction of the problem with instructions

The error message seems to relate to the following code.

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

@Injectable()
export class MembersService {
  constructor(
    @InjectRepository(Members)
    private readonly membersRepository: Repository<Members>,
  ) {}

  async findAll(): Promise<Members[]> {
    return await this.membersRepository.find();
  }
...
}

What is the motivation / use case for changing the behavior?

Nestjs server boots and full CRUD returns.

Environment


Nest version: 5.0.0 / @nestjs/typeorm 3.0.0 / TypeORM 0.2.6 
/ Express 4.16.3 / RxJS 6.1.0 / @nestjs/cli 5.1.2

For Tooling issues:
- Node version: 8.11.2
- Platform:  Ubuntu server 16.04.4

Others:
IDE Webstorm 2018.1.3 (the latest).
question 🙌

All 16 comments

Hi @svstartuplab,
I cannot reproduce your issue :( I created an integration test here:
https://github.com/nestjs/nest/tree/master/integration/typeorm
Also, I have tried with this sample:
https://github.com/nestjs/nest/tree/master/sample/05-sql-typeorm
Everything works like a charm

Are you sure that all @nestjs packages are updated to 5.0.0 (without any tag)?

I've looked through your examples and can find no differences in code but I still get the same message even in a new clean folder, /nestjs5 explained below. I'm currently developing in 4.6 and all is well. Same setup but in the /nestjs folder so the Ubuntu environment above the two Nestjs folders is the same such as Node. I also suspect dependencies but finding the issue is difficult. A totally clean setup should fix that but didn't. I included more of my code below.

What else is there besides the cli's package json dependencies and typescript?

Dependences in the development folder on Ubuntu 16.04:

[email protected] /home/server/nestjs5
├── @nestjs/[email protected]
├── @nestjs/[email protected]
├── @nestjs/[email protected]
├── @nestjs/[email protected]
├── @nestjs/[email protected]
├── @nestjs/[email protected]
├── @types/[email protected]
├── @types/[email protected]
├── @types/[email protected]
├── @types/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

1) I setup a new project:

$ npm i -g @nestjs/cli  // installed v5.1.2
$ nest new nestjs5

2) npm run start and it worked. ^c to kill it.

3) Installed TypeORM:

$ npm install --save @nestjs/typeorm typeorm pg

4) Copied my code, which isn't much, into /nestjs5/src and added the modules to app.module:

import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';

import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';

import { AppController } from './app.controller';
import { LoggerMiddleware } from './logger.middleware';

import { MembersModule } from './members/members.module';
import { MembersController } from './members/members.controller';
import { MembersService } from './members/members.service';

import { Member_categoriesModule } from './member_categories/member_categories.module';
import { Member_categoriesController } from './member_categories/member_categories.controller';
import { Member_categoriesService } from './member_categories/member_categories.service';

import { SkillsModule } from './skills/skills.module';
import { SkillsController } from './skills/skills.controller';
import { SkillsService } from './skills/skills.service';
// import { AppService } from './app.service';


@Module({
  imports: [
    TypeOrmModule.forRoot(),
    MembersModule,
    Member_categoriesModule,
    SkillsModule
  ],
  controllers: [
    AppController,
    MembersController,
    Member_categoriesController,
    SkillsController
  ],
  providers: [
    // AppService,
    MembersService,
    SkillsService,
    Member_categoriesService,
  ]
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes(MembersController, Member_categoriesController, SkillsController);
  }
  constructor(private readonly connection: Connection) {

    function connectToDB(connection) {
      if(connection === true) {
        console.log('Connected!');
      } else {
        console.error('Connection Error!');
      }
    }
    connectToDB(connection);
  }
}

5) Refactored module components to providers for my three modules:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MembersService } from './members.service';
import { MembersController } from './members.controller';
import { Members } from './members.entity';

@Module({
  imports: [TypeOrmModule.forFeature([Members])],
  providers: [MembersService],
  controllers: [MembersController],
})

export class MembersModule {}

6) Changed @Component to @Injectable in my three modules:

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

@Injectable()
export class MembersService {
  constructor(
    @InjectRepository(Members)
    private readonly membersRepository: Repository<Members>,
  ) {}

  async findAll(): Promise<Members[]> {
    return await this.membersRepository.find();
  }

  async findItem(recordId): Promise<Members> {
    return await this.membersRepository.findOne(recordId);
  }

  async addItem(recordData): Promise<Members> {
    return await this.membersRepository.save(recordData);
  }

  async updateItem(recordId, recordUpdate): Promise<any> {
    return await this.membersRepository.update(recordId.id, recordUpdate);
  }

  async deleteItem(recordId: number) {
    return await this.membersRepository.delete(recordId);
  }
}

7) I did nothing to main.ts but commented out app.service in that module and in app.controller. I don't need it but also this line fails to find '@nestjs/common' although this isn't a problem in any of my other service modules: import { Injectable } from '@nestjs/common'; This was installed with the cli. Very strange and maybe hints at the main problem.

8) It appears that nothing has changed for Entity from 4.6 to 5.0:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Members {
  @PrimaryGeneratedColumn()
  member_id: number;

  @Column({ length: 100 })
  first_name: string;

  @Column({ length: 1 })
  middle_initial: string;

  @Column({ length: 100 })
  last_name: string;

  @Column({ length: 100 })
  main_skill_title: string;
...
}

Hello!
It seems that I am facing the same problem.

@Global()
@Module({
  imports: [
    TypeOrmModule.forRoot(),
    AuthModule,
    EmailConfirmationModule,
    RegistrationModule,
    UserModule,
  ],
  providers: [configProvider, ejsProvider, mailerProvider, redisProvider],
  exports: [configProvider, ejsProvider, mailerProvider, redisProvider],
})
export class AppModule {
}
@Module({
  controllers: [UserController],
  exports: [RolesGuard, UserService],
  imports: [TypeOrmModule.forFeature([User, Role])],
  providers: [RolesGuard, UserService],
})
export class UserModule {
}
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
  ) {
  }
  //...
}

When I start the application, I get the following error:

[Nest] 25122   - 5/31/2018, 12:27:51 AM   [NestFactory] Starting Nest application...
[Nest] 25122   - 5/31/2018, 12:27:51 AM   [InstanceLoader] TypeOrmModule dependencies initialized +69ms
[Nest] 25122   - 5/31/2018, 12:27:51 AM   [ExceptionHandler] Nest can't resolve dependencies of the UserService (?, +). Please verify whether [0] argument is available in the current context.
Error: Nest can't resolve dependencies of the UserService (?, +). Please verify whether [0] argument is available in the current context.
    at Injector.lookupComponentInExports (/Users/Vadim/Projects/go-plans-api/node_modules/@nestjs/core/injector/injector.js:129:19)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:746:11)
    at startup (internal/bootstrap/node.js:238:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
[Nest] 25122   - 5/31/2018, 12:27:51 AM   [InstanceLoader] AppModule dependencies initialized +1ms
 1: node::Abort() [/Users/Vadim/.nvm/versions/node/v10.3.0/bin/node]
 2: node::Chdir(v8::FunctionCallbackInfo<v8::Value> const&) [/Users/Vadim/.nvm/versions/node/v10.3.0/bin/node]
 3: v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo*) [/Users/Vadim/.nvm/versions/node/v10.3.0/bin/node]
 4: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/Users/Vadim/.nvm/versions/node/v10.3.0/bin/node]
 5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/Users/Vadim/.nvm/versions/node/v10.3.0/bin/node]
 6: 0x3ee5f238427d

Node.js version: 10.3.0 (I've tried to use v8.11.2 - the same error).
TypeScript version: 2.8.4.

"@nestjs/common": "5.0.1",
"@nestjs/core": "5.0.1",
"@nestjs/passport": "1.0.10",
"@nestjs/swagger": "2.0.2",
"@nestjs/testing": "5.0.1",
"@nestjs/typeorm": "5.0.0",

Thanks for reporting this Vadim. I had to roll back to 4.6 and it is working very well. I'll wait for this issue to be fixed before trying to upgrade again.

Same here

Hum... just in case but couldn't be due to typeorm type use ?
I saw some Entity / Repository using @nestjs/typeorm and not typeorm module directly...
Like I said just in case... never used it...

Thanks @ThomRick but TypeORM is in my package.json and installed "├── [email protected]"

Is there any news?

We cannot help without repository that reproduces this issue. I tried with few apps already, everything works fine. Is there a chance to share a repo with me?

Kamil, I accidentally seemed to have reproduced it in 4.6 yesterday, and fixed it. I'll try to fix it in 5.0 probably today. The fix was to move a var out of the constructor to above it in the class. I'll get back to you soon.

The problem is that the 4.6 app.module is very different than the 5.0 module, more than is covered in the Migration section of the docs. The new docs for TypeORM are correct but I never knew to look there. My original is above. The refactored app.module is below and it works. Basically include only the module imports, no services or controllers unless needed elsewhere in your code, and remove the TypeORM code at the bottom. I can finally start using the 5.0 version.

@Module({
  imports: [
    TypeOrmModule.forRoot(),
    MembersModule,
    Member_categoriesModule,
    SkillsModule
  ],
  controllers: [
  ],
  exports: [
  ],
  providers: [
  ]
})

export class AppModule{}

I've solved the problem! It didn't work because I tried to import a service from another module instead of this module... :)

Vadim, yes, this issue seems to be related to modules and injections, not the component referenced in the error message, at least not directly that component. Hopefully our solutions will help others. I'm sure you lost a lot of time as I have. OK, now we move on to the next problem to solve :-)

Can you please give a code example of how you fixed the problem?

I had the same issue and resolved it thanks to @vadim-shilov.

It appears when you generate a service with the CLI but don't reference a module, the CLI registers the services as providers in App Module (not the specific module you are using them in). When using TypeORM repository pattern and trying to inject the repository in the constructor (of the service), while they are providers in App Module you get this error. I assume its something to do with the App Module being forroot(), not forfeature()?

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings