#Database Module with TypeORM throws dependency related exception during application startup.

5 messages · Page 1 of 1 (latest)

lament abyss
#

I am working on a solution with multiple APIs that connects to the same database. I want to reuse the database entities so I decided to create a Database Module that include the entities and a Dynamic Module that configures TypeORM. And I also wanted to share this as a npm package. For now I am installing the npm package directly from my local disk. I created the following DatabaseModule and this is included in the npm package along with the entities for the database model.

import { DynamicModule, Module } from '@nestjs/common';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';

@Module({})
export class DatabaseModule {
  static register(options: TypeOrmModuleOptions): DynamicModule {
    return {
      module: DatabaseModule,
      imports: [
        TypeOrmModule.forRoot({
          ...options,
          entities: [__dirname + './models/**/*.model{.ts,.js}'],
        }),
      ],
    };
  }
}

Once I install the npm package on my API project, I am importing the new DatabaseModule in my AppModule imports like this.

@Module({
  imports: [
    ConfigModule.forRoot(),
    DatabaseModule.register({
      type: 'mssql',
      host: process.env.DATABASE_HOST,
      port: +process.env.DATABASE_PORT,
      username: process.env.DATABASE_USERNAME,
      password: process.env.DATABASE_PASSWORD,
      database: process.env.DATABASE_NAME,
      options: {
        trustServerCertificate: Boolean(
          process.env.DATABASE_TRUST_SERVER_CERTIFICATES,
        ),
      },
    }),    
  ],
})
export class AppModule {}

When I try to run the API app it fails with the following error message.
ERROR [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmCoreModule (TypeOrmModuleOptions, ?). Please make sure that the argument ModuleRef at index [1] is available in the TypeOrmCoreModule context.

Any help pointing me in the right direction is appreciated. Want to understand what I am doing wrong here.

tranquil schooner
#

For now I am installing the npm package directly from my local disk?
This is the issue. Locally installing npm packages doesn't respect peerDeps for packages (you do have the @nestjs/* packages as peerDeps, right?) and you get these issues where ModuleRef instanceof ModuleRef === false because of how JS Realms work.

Either pack the package up as a tarball and install the tar as that will resp[ect the peerDeps, or copy the dist of your package, and its package.json to the node_modules/<package-name> of the application where you want to use it

lament abyss
#

Yes, I have the nest packages as peerDependencies. I will publish the package and try it out. Thank you very much for the help.

lament abyss
tranquil schooner
#

We've answered several questions like this on this server