egg icon indicating copy to clipboard operation
egg copied to clipboard

如何在config.default.ts 中获取 app 对象?

Open lengyuxuan opened this issue 2 years ago • 1 comments

请详细告知你的新点子(Nice Ideas):

我正在开发一个消息队列封装的插件,遇到了如下问题:

  1. 向 app 挂载 consumer 实例,实例化 consumer 时需要提供 ctx,目前工作正常:
// {plugin}/app.ts
module.exports = (app: Application) => {
  const consumerDir = path.join(app.baseDir, 'app/consumer');
  app.loader.loadToApp(consumerDir, 'consumer', {
    caseStyle: 'upper',
    initializer(factory: new (ctx: Context, redis: Redis, options: ConsumerOptions) => Consumer) {
      const ctx = app.createAnonymousContext();
      return new factory(ctx, app.redis, app.config.consumer[factory.name]);
    },
  });
};
  1. 向 app 挂载 producer 实例,producer 需要在其他文件中调用(例如 controller 或 service),为了提供类型提示,我使用了 config.customLoader 来自动生成 d.ts,但我仍需提供 ctx 实例,我却无法拿到 app 去创建它:
// {plugin}/config/config.default.ts
export default () => {
  const config = {} as PowerPartial<EggAppConfig>;

  config.customLoader = {
    producer: {
      directory: 'app/producer',
      inject: 'app',
      caseStyle: 'upper',
      initializer(factory: typeof Producer) {
        // 我应当用什么方式获取 app 呢?
        const ctx = app.createAnonymousContext();
        return new factory(ctx, app.redis, app.config.producer[factory.name]);
      },
    },
  };
  return config;
};

我查看了部分源码,发现此处如果 inject.length !== 0 就不会向 config.default.ts 中注入 app 对象了。

image

请问我是有其他方式在 config.default.ts 中拿到 app 呢,还是可以在 app.ts 中通过一些 api 提供 ts 类型提示呢?

lengyuxuan avatar Aug 15 '23 02:08 lengyuxuan

可以参考 https://github.com/eggjs/egg-schedule ,封装一个 mq 的 Subscription 编程界面

fengmk2 avatar Aug 15 '23 05:08 fengmk2