簡體   English   中英

NestJS 裝飾器 - 這是未定義的上下文

[英]NestJS Decorator - Context this is undefined

我們正在嘗試構建我們自己的 Kafka 集成。 我們使用裝飾器捕獲對函數的引用,然后嘗試在從 Kafka 接收到新消息時在其他地方觸發它

裝飾器:

export const SUBSCRIBER_FN_REF_MAP = new Map();
export const SUBSCRIBER_OBJ_REF_MAP = new Map();

export function SubscribeTo(topic) {
    return (target, propertyKey, descriptor) => {
        const originalMethod = target[propertyKey];
        SUBSCRIBER_FN_REF_MAP.set(topic, originalMethod);
        SUBSCRIBER_OBJ_REF_MAP.set(topic, target);
        return descriptor;
    };
}

當在我們注入一些存儲庫的服務中使用它時,上下文總是未定義的:

@Injectable()
export class KafkaEventsListenerService {

  constructor(
    private readonly messageUserRepository: MessageUserRepository
  ) {
  }

  @SubscribeTo(DANCEFLAVORSAPI_USER_CREATED_TOPIC)
  async onUserCreated(payload: string): Promise<void> {
    console.log('[KafkaConsumer receiving ' + DANCEFLAVORSAPI_USER_CREATED_TOPIC + ']: ', payload);

    console.log(await this.messageUserRepository.findAll());

  }

}
@Injectable()
export class MessageUserRepository {
  constructor(
    @InjectRepository(MessageUserEntity)
    private readonly repository: Repository<MessageUserEntity>
  ) {}

  async findAll(): Promise<MessageUserEntity[]>{
    return await this.repository.find();
  }
}

存儲庫函數調用導致錯誤:

無法讀取未定義的屬性“findAll”

當我刪除裝飾器時,它可以工作。

有人能幫助我嗎?

根據來自裝飾器的代碼示例,您似乎正在嘗試捕獲對類方法的引用,然后在其他地方(在 NestJS 生命周期之外)調用它。

在 NestJS 依賴注入容器中的所有東西都被引導之前,裝飾器會立即運行,因此類的構造函數參數將不會被解析或可用。

我建議您重新考慮裝飾器的架構,並將內容移到應用程序的onModuleInit ,以正確發現和綁定 Kafka 處理程序。

我構建了@golevelup/nestjs-rabbitmq包,它執行與您在這里嘗試完成的相同類型的事情,但使用 rabbitmq 而不是 Kafka。

您應該采取的基本步驟是:

@golevelup/nestjs-discovery包使掃描所有提供者及其方法以查找裝飾器元數據變得非常容易(免責聲明,我是作者)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM