NestJS How to configure middleware with async/await?

北城余情 提交于 2019-12-24 13:01:39

问题


I'm trying to use bull-arena in a NestJS app.

export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    const queues = this.createArenaQueues();
    const arena = Arena({ queues }, { disableListen: true });
    consumer.apply(arena).forRoutes('/system/queues');
  }

  createArenaQueues() {
    return [
      {
        name: 'Notification_Emailer',
        hostId: 'MyAwesomeQueues',
        url: 'redis://localhost',
      },
    ];
}
}

This works!

But I need to use async/await for createArenaQueues(), due to loading queues from db.

export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    const queues = await this.createArenaQueues();   //await here
    const arena = Arena({ queues }, { disableListen: true });
    consumer.apply(arena).forRoutes('/system/queues');
  }

  async createArenaQueues() {                       // async here
    return [
      {
        name: 'Notification_Emailer',
        hostId: 'MyAwesomeQueues',
        url: 'redis://localhost',
      },
    ];
  }
}

Doesn't work!

So, the question, how to handle this?

It wold be cool to run arena from "System" controller, but I couldn't figure out a way to do it.

Also, I tried to move arena to standalone middleware, but dont know, what I should to do in the end: return something like res.send(arena) or what?

Easiest way to handle this, is async configure support, but it not implemented.


回答1:


You can create a custom provider for your arenaQueues that is created asynchronously:

Add the custom provider to your AppModule's providers:

providers: [
  ArenaService,
  {
    provide: 'arenaQueues',
    useFactory: async (arenaService: ArenaService) => arenaService.createArenaQueues(),
    inject: [ArenaService],
  },
],

and then inject the arenaQueues in your AppModule:

export class AppModule {
  constructor(@Inject('arenaQueues') private queues) {}

  configure(consumer: MiddlewareConsumer) {
    // Now, you can use the asynchronously created this.queues here
    const arena = Arena({ queues: this.queues }, { disableListen: true });
    consumer.apply(arena).forRoutes('/system/queues');
  }


来源:https://stackoverflow.com/questions/56239773/nestjs-how-to-configure-middleware-with-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!