Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest can't resolve DataSource as dependency

I've had a problem with dependencies in NestJS. On launch my NestJS app, compiler throw me this:

[Nest] 16004  - 09.04.2022, 16:14:46   ERROR [ExceptionHandler] Nest can't resolve dependencies of the AccountService (MailingService, ?). Please make sure that the argument DataSource at index [1] is available in the AccountModule context.

Can someone tell me what I'm doing wrong?

Here is my modules:

@Module({
  imports: [],
  providers: [AccountService, MailingService],
  controllers: [AccountController],
  exports: []
})
export class AccountModule {}

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useClass: TypeOrmConfigService,
    }),
  ],
})
export class DatabaseModule {}

@Module({
  imports: [
    DatabaseModule,
    ConfigModule.forRoot({
      envFilePath: '.env',
    }),
    ScheduleModule.forRoot(),
    AccountModule,
    AuthModule,
    MailingModule],
  controllers: [AppController],
  providers: [],
})
export class AppModule { }

thanks for any help!

PS. DataSource is a class from TypeORM to make query, earlier it was Connection class

like image 352
BokuNoHeeeero Avatar asked Dec 29 '25 00:12

BokuNoHeeeero


2 Answers

The first step we have to create database providers.

database.providers.ts

import { DataSource } from 'typeorm';

export const databaseProviders = [
    {
        provide: DataSource,
        useFactory: async () => {
            // You can inject config service to provide dynamic DataSourceOptions
            const dataSource = new DataSource({
                type: 'mysql',
                host: 'localhost',
                port: 3306,
                username: 'root',
                password: 'root',
                database: 'test',
                entities: [
                    __dirname + '/../**/*.entity{.ts,.js}',
                ],
                synchronize: true,
            });
            try {
                if (!dataSource.isInitialized) {
                    await dataSource.initialize();
                }
            } catch (error) {
                console.error(error?.message);
            }
            return dataSource;
        }
    }
];

Now we can import/export our database providers inside DatabaseModule.

database.module.ts

import { Module } from '@nestjs/common';
import { databaseProviders } from './database.providers';

@Module({
    providers: [...databaseProviders],
    exports: [...databaseProviders],
})
export class DatabaseModule {}

Now, We can Inject DataSouce dependency into any feature module. i.e. photo.module.ts

Note: Do not forgot to import DatabaseModule inside PhotoModule.

like image 74
Rahul Rathore Avatar answered Dec 31 '25 15:12

Rahul Rathore


The docs are not very clear on this, but i figured out you can use the @InjectDataSource() decorator from @nest/typeorm package.

example:

import { DataSource } from 'typeorm';
import { InjectDataSource } from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forRoot(), UsersModule],
})
export class AppModule {
  constructor(
    @InjectDataSource()
    private dataSource: DataSource
  ) {}
}
like image 44
Julez Avatar answered Dec 31 '25 15:12

Julez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!