简体   繁体   中英

Nestjs Subscriber +TypeOrm Injection through yml files

How can we inject connection dependencies of the subscriber with yml files.

my files are: ormconfig.yml

default:
    type: 'postgres'
    host: 'localhost'
    port: 5432
    username: 'postgres'
    password: 'root'
    database: 'hiring_db'
    entities: ["dist/**/*.entity{.ts,.js}"]
    synchronize: true
    logging: ["query","error"]
    logger: "file"
    extra: { timezone: "+5:30" }
    migrations: ["src/migrations/*.ts"]
    cli:   {
        migrationDir: 'src/migrations'
    }
    subscribers: ["src/**/*.subscriber{.ts,.js}"]

JobPostingModule.ts

import { Module } from '@nestjs/common';
import { JobPostingController } from './job-posting.controller';
import { JobPostingService } from './job-posting.service';
import { AuthModule } from '../auth/auth.module';
import { RecruitmentService } from '../recruitment/recruitment.service';

@Module({
  imports: [
    AuthModule
  ],
  controllers: [JobPostingController],
  providers: [JobPostingService, RecruitmentService]
})
export class JobPostingModule {}

JobSubscriber.ts

import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import { Jobs } from 'src/entities/job-posting.entity';
import { Connection, EntitySubscriberInterface, getConnection, InsertEvent, UpdateEvent } from 'typeorm';
import { JobPostingService } from './job-posting.service';


@Injectable()
export class JobSubscriber implements EntitySubscriberInterface {
  
  constructor(private readonly connection: Connection) {
    connection.subscribers.push(this); // <---- THIS 
   
}

  listenTo() {
    return Jobs;
  }

  afterInsert(event: InsertEvent<Jobs>) {
    console.log('Hi guys!');
  };

  afterUpdate(event: UpdateEvent<any>) {
    console.log('Hi guys!');
  }

}

I am getting this error Nest can't resolve dependencies of the JobSubscriber (?). Please make sure that the argument Connection at index [0] is available in the AppModule context.

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

You can refer to the official NestJS documentation for this problem.

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

@Module({
  imports: [
    TypeOrmModule.forRoot(),
  ],
})
export class AppModule {}

Once you imported the TypeOrmModule you can use Connection as a provider everywhere.

do not use subscribers: ["src/**/*.subscriber{.ts,.js}"]

just add connection.subscribers.push(this); logic

and use the subscriber as a module Provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM