GreatLaboratory
GreatLaboratory

Reputation: 41

NestJS/TypeORM : custom repository + multiple databases

I make code by nestjs docs (custom repository, multiple databases)

And here is my code.

// app.module.ts
@Module({
    imports: [
        TypeOrmModule.forRoot({
            name: 'MYSQL_CONNECTION',
            type: 'mysql',
            port: 3306,
            entities: [AwsTest],
            logger: new MysqlLogger(),
            synchronize: false,
            extra: {
                connectionLimit: 10,
            },
        }),
        TypeOrmModule.forRoot({
            name: 'ORACLE_CONNECTION',
            type: 'oracle',
            entities: [],
            synchronize: false,
            logger: new OracleLogger(),
            extra: {
                connectionLimit: 10,
            },
        }),
        TestModule,
    ],
    providers: [Logger],
})
export class AppModule implements NestModule {}
// test.module.ts
@Module({
    imports: [TypeOrmModule.forFeature([TestRepository], 'MYSQL_CONNECTION')],
    providers: [TestService],
    controllers: [TestController],
})
export class TestModule {}
// test.service.ts
@Injectable()
export class TestService {
    constructor(private readonly testRepository: TestRepository) {}
    async getAwsTest() {
        return await this.testRepository.getAwsTest()
    }
}
// test.repository.ts
@EntityRepository(AwsTest)
export class TestRepository extends BaseRepository<AwsTest> {
    async getAwsTest() {
        return await this.find()
    }
}
// aws-test.entity.ts
@Entity('test', { database: 'report' })
export class AwsTest {
    constructor(name: string, address: string) {
        this._name = name
        this._address = address
    }

    @Column('varchar', { primary: true, name: 'name' })
    readonly _name: string

    @Column('varchar', { name: 'address' })
    readonly _address: string
}

In this situation, nest application is not running. Here is error console.

Nest can't resolve dependencies of the TestService (?). Please make sure that the argument TestRepository at index [0] is available in the TestModule context.

Potential solutions:

If TestRepository is a provider, is it part of the current TestModule?
If TestRepository is exported from a separate @Module, is that module imported within TestModule? @Module({ imports: [ /* the Module containing TestRepository */ ] })

I need your help..... (In app.module.ts, i make invisible critical information like host, username, password, database, sid...)

Upvotes: 4

Views: 4610

Answers (2)

Sanket Jariwala
Sanket Jariwala

Reputation: 11

Add this code into app.module.ts file

@Module({
  // Database connection
  TypeOrmModule.forFeature([TestRepository], 'MYSQL_CONNECTION')
})

Upvotes: 1

swirkens
swirkens

Reputation: 31

Try injecting your repository like this:

constructor(
  @InjectRepository(AwsTest, 'MYSQL_CONNECTION') private readonly testRepository: TestRepository,
) { }

Upvotes: 3

Related Questions