NestJS 中的嵌套动态模块

  • Debugging incident: Spent hours debugging an incident due to misunderstanding of dynamic modules this week and wants to share learnings.
  • Dynamic modules usage: Allow modules to be imported with customized configuration. In this case, using TemporalModule.registerWorkerAsync from nestjs-temporal library to register a Temporal worker. There are about a dozen such registrations with different responsibilities.
  • Problem with duplicated code: There is a lot of duplicated code in the call that can lead to using an incorrect task queue name and workflows not being executed.
  • Solution attempt: Wrote a function registerTemporalWorker to create the dynamic module but it didn't work as only one worker was created.
  • Final solution: Wrapped the dynamic module in another dynamic module by adding a provideInjectionTokensFrom property. Now the options passed to useFactory are injected and a new module is created via useFactory for each worker. It's much safer in preventing invalid queue configurations and minimizes duplication. Also added an ESLint rule to prevent using the incorrect module or worker options.
  • Search result: A search on Google for provideInjectionTokensFrom yields only a few hits and one is a closed GitHub ticket. Hoping this post will be helpful to others.
阅读 16
0 条评论