首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NestJS在TypeORMModule.forRootAsync中使用connectionName时引发依赖异常

NestJS在TypeORMModule.forRootAsync中使用connectionName时引发依赖异常
EN

Stack Overflow用户
提问于 2022-09-10 10:09:07
回答 1查看 134关注 0票数 0

你能帮我找出我在这里做错了什么吗?

我试图在name中添加TypeORM.forRootAsync属性,但是当我这样做时,我的应用程序开始抛出依赖异常。

这是我的app.module文件:

代码语言:javascript
运行
复制
@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 {}

下面是我的一个模块:

代码语言:javascript
运行
复制
@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 {}

当我向TypeORM.forRootAsync调用添加名称时,它将开始抛出此异常:

代码语言:javascript
运行
复制
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 */ ]
  })

这是我的账户仓库:

代码语言:javascript
运行
复制
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 };
    }

我遗漏了什么?

EN

回答 1

Stack Overflow用户

发布于 2022-09-11 01:45:01

如果您使用的是一个命名连接(就像您使用的那样),您需要将连接名添加到TypeormModule.forFeature() (就像您有)@InjectRepository()中,作为这两个方法的第二个参数。所以你需要@InjectRepository(Account, 'psql')

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73670955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档