我有一个NestJS订阅服务器,可以监听任何创建,更新或删除事件(TypeORM)。当这些事件之一被触发时,我想使用注入的服务来创建新的修订条目。
但是,似乎我无法在订户内部加载依赖项,并且服务由于未定义而返回
关键文件:
app.module.ts
@Module({
imports: [
HttpModule,
TypeOrmModule.forRoot({
type: (process.env.DB_TYPE as any) || 'postgres',
host: process.env.DB_HOST || '127.0.0.1',
port: (process.env.DB_PORT as any) || 5432,
username: process.env.DB_USER || 'root',
password: process.env.DB_PASS || '',
database: process.env.DB_NAME || 'test',
entities: [join(__dirname, '**/**.entity{.ts,.js}')],
synchronize: true,
logging: 'all',
logger: 'advanced-console',
subscribers: [EntityModificationSubscriber],
}),
TypeOrmModule.forFeature([
RevisionEntity,
]),
TerminusModule.forRootAsync({
// Inject the TypeOrmHealthIndicator provided by nestjs/terminus
inject: [TypeOrmHealthIndicator, MicroserviceHealthIndicator],
useFactory: (db, msg) => getTerminusOptions(db, msg),
}),
GraphQLModule.forRoot({
debug: true,
playground: true,
typePaths: ['./**/*.graphql'],
}),
],
controllers: [AppController],
providers: [
RevisionService,
EntityModificationSubscriber,
],
})
entity_modification_subscriber.ts
import {EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent} from 'typeorm';
import {RevisionEntity, RevisonEntityStatus} from '../entities/revison.entity';
import {RevisionService} from '../services/revisions.service';
import {Injectable} from '@nestjs/common';
@Injectable()
@EventSubscriber()
export class EntityModificationSubscriber implements EntitySubscriberInterface {
constructor(private revisionService: RevisionService) {
}
// tslint:disable-next-line:no-empty
afterInsert(event: InsertEvent<any>): Promise<any> | void {
const revision = new RevisionEntity();
revision.action = RevisonEntityStatus.Created;
}
afterUpdate(event: UpdateEvent<any>): Promise<any> | void {
}
// tslint:disable-next-line:no-empty
afterRemove(event: RemoveEvent<any>) {
// this.revisionService.createRevisionEntry(revision);
}
}
答案 0 :(得分:4)
我发现使用NestJS向订阅服务器中注入依赖项的唯一方法是不在TypeORM配置中注册该订阅服务器。我将其手动订阅到订阅者构造函数的TypeORM连接中。
aRef
然后在TypeORM模块配置(TypeOrmModule.forRoot)上的app.module中。 删除行:
// Opt-in to interactivity
square.interactive = true;
square.buttonMode = true;
它解决了我,希望对他人有所帮助。 您可以在一些NestJS问题/拉取请求中找到有关此问题的讨论。