NestJS throws dependency exception when using connectionName in TypeORMModule.forRootAsync

Viewed 41

can you help me figure out what I am doing wrong here?

I am trying to add the name property in TypeORM.forRootAsync, but when I do that, my app starts throwing dependency exceptions.

Here is my app.module file:

@Module({
    imports: [
        UsersModule,
        TypeOrmModule.forRootAsync({
            name: 'psql',  // ------> this is the line that throws the error
            useFactory: () => {
                return {
                    type: 'postgres',
                    host: process.env.POSTGRES_DATABASE_HOST,
                    port: parseInt(process.env.POSTGRES_DATABASE_PORT),
                    username: process.env.POSTGRES_DATABASE_USERNAME,
                    password: process.env.POSTGRES_DATABASE_PASSWORD,
                    database: process.env.POSTGRES_DATABASE_NAME,
                    logging: false,
                    autoLoadEntities: true,
                    synchronize: false,
                };
            },
        }),
        GroupsModule,
        EventsModule,
        AccountsModule,
        ConfigModule.forRoot({ isGlobal: true }),
        AuthModule,
        IntegrationsModule,
        MailModule,
    ],
    controllers: [AppController],
    providers: [AppService],
    exports: [TypeOrmModule],
})
export class AppModule {}

Here is one of my modules:

@Module({
    imports: [
        TypeOrmModule.forFeature([Account, Project, ApiKey, Operator, ProjectRole, Session], 'psql'), // ---------------> adding this didn't fix it
        CqrsModule,
        ConfigModule,
        MailModule,
        BullModule.registerQueue({
            name: 'projects',
        }),
        JwtModule.register({
            secret: process.env.JWT_SECRET,
            signOptions: { expiresIn: '30d' },
        }),
    ],
    controllers: [AccountsController, ApikeysController, ProjectsController, OperatorsController],
    exports: [ApikeysService, ApiKeyRepository, AccountRepository, ProjectRepository, OperatorsService],
    providers: [...],
})
export class AccountsModule {}

When I add name to the TypeORM.forRootAsync call, it starts throwing this exception:

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

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

This is my Account Repository:

import { AggregateRoot, EventBus } from '@nestjs/cqrs';
import { v4 as uuidv4 } from 'uuid';
import { HttpException, HttpStatus, Logger } from '@nestjs/common';
import { Account } from '../entities/account.entity';
import { AccountCreatedEvent } from '../events/account-created.event';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

export class AccountRepository extends AggregateRoot {
    private readonly logger = new Logger('Account Repository');
    constructor(private eventBus: EventBus, @InjectRepository(Account) private readonly accountRepository: Repository<Account>) {
        super();
    }

    async create(name: string, slug: string): Promise<Account> {
        this.logger.debug(`Checking if account exists`);
        if (await this.get({ slug })) {
            throw new HttpException('Account slug already exists', HttpStatus.BAD_REQUEST);
        }

        const id = uuidv4();
        const createdAt = new Date();

        const account: Account = this.accountRepository.create({ id, name, slug, createdAt });
        await this.accountRepository.save(account);

        this.logger.debug(`Posting AccountCreatedEvent`);
        this.eventBus.publish(new AccountCreatedEvent(id));

        return { id, slug, name, createdAt };
    }

What am I missing?

1 Answers

If you're using a named connection (like you are) you need to add the connection name to TypeormModule.forFeature() (like you have) and to @InjectRepository() as the second parameter of both methods. So you need @InjectRepository(Account, 'psql')

Related