Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lengyuxuan opened this issue Aug 15, 2023 · 1 comment
Open

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

lengyuxuan opened this issue Aug 15, 2023 · 1 comment

Comments

@lengyuxuan
Copy link

lengyuxuan commented Aug 15, 2023

请详细告知你的新点子(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 类型提示呢?

@fengmk2
Copy link
Member

fengmk2 commented Aug 15, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants