You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS将Factory提供者注入ThrottlerModule报错解决方案

问题根因

报错来自两个核心写法错误:

  • 注入自定义Provider时使用了错误的Token:你在inject数组中传入的是整个Provider配置对象ApiConfigFactory,但Nest容器中绑定该实例的Token是你定义的字符串常量API_CONFIG_FACTORY,容器无法匹配到对应依赖。
  • 异步Provider逻辑冗余:你在工厂函数中额外包装了一层带generate方法的对象,既没有直接返回初始化完成的配置服务实例,也没有在返回对象上实现get方法,就算注入成功也会触发方法不存在的运行时错误。
修复步骤

1. 重构配置服务与异步Provider

去掉多余的包装层,在异步工厂中直接初始化并返回配置服务实例,补上缺失的配置读取方法:

import { Injectable, Provider } from '@nestjs/common';
@Injectable()
export class ApiConfigService {
  private config: Record<string, any> = {};

  public async init() {
    // 此处替换为实际远程配置拉取逻辑
    await new Promise((resolve) => setTimeout(resolve, 500));
    this.config = {
      throttle_api_ttl: 60,
      throttle_api_limit: 10,
      // 其余配置项
    };
  }

  get(key: string) {
    return this.config[key];
  }
}

// 导出注入Token,所有注入该实例的位置都使用这个常量
export const API_CONFIG_SERVICE = 'API_CONFIG_SERVICE';

export const ApiConfigServiceProvider: Provider = {
  provide: API_CONFIG_SERVICE,
  useFactory: async () => {
    const service = new ApiConfigService();
    await service.init();
    return service;
  },
};

2. 修正配置模块的导出

import { Module } from '@nestjs/common';
import { ApiConfigServiceProvider } from './api-config.service';

@Module({
  providers: [ApiConfigServiceProvider],
  exports: [ApiConfigServiceProvider],
})
export class ApiConfigModule {}

3. 修正ThrottlerModule的异步配置

传入正确的注入Token,直接使用返回的配置服务实例读取参数:

import { Module } from '@nestjs/common';
import { ThrottlerModule } from '@nestjs/throttler';
import { ApiConfigModule } from './api-config/api-config.module';
import { API_CONFIG_SERVICE } from './api-config/api-config.service';

@Module({
  imports: [
    ApiConfigModule,
    ThrottlerModule.forRootAsync({
      imports: [ApiConfigModule],
      inject: [API_CONFIG_SERVICE],
      useFactory: (config) => {
        return {
          ttl: config.get('throttle_api_ttl'),
          limit: config.get('throttle_api_limit'),
        };
      },
    }),
  ],
})
export class AppModule {}
说明

Nest原生支持异步Provider,useFactory如果返回Promise,Nest会等待实例初始化完成后再将其注入到所有依赖它的模块、服务中,不需要额外封装生成器方法。注入依赖时必须使用注册Provider时指定的provide值作为Token,不能直接传入整个Provider配置对象。

内容的提问来源于stack exchange,提问作者Ruslan Plastun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 06:48:21