nestjs 动态模块

852 阅读1分钟

我们定义一个模块套路是

@Modules({
 imports:[其他模块],
 providers:[。。。一些提供者],
 exports:[导出提供者给其他模块使用]
})

export classs 动态模块{
}

有时候需要根据【条件】 生成对应不同条件的提供者 不是【固定的】 这个使用就需要动态了 nestjs提供的语法套路是使用

static forRoot(options){
    var proviers=[]
    if(options){
    proviers=[12334]
    }
         return {
          proviers:[proviers],
          exports:[proviers]
         }
}

return的东西就是你这个模块动态提供的

其他的模块要使用你这个模块

@Modules({
imports:[动态模块.forRoot(参数)],
})
class 我是一个模块{
}

然后你可以在【我是一个模块】中使用动态模块提供的proviers

经典案例 动态根据forroot()参数生成不同的配置文件

需求:根据 参数 env.development, env.product,读取对应的配置文件, 此模块提供一个configservice configservice.get('key') 可以获取对应的配置信息

实现如下

@Modules({
 
})
export class ConfigModules(){
  static forRoot(path:string){

 


  return {
   providers:[{
    provider:'我是配置文件路径',
    useValue:path  //这个key value 到时候给configservice注入使用
  },ConfigService],
  exports:[ConfigService]
  }

  }
}

@Injectable()
classs ConfigService{
    hashmap:{[key:string]:string}
  
  
  constructor( @Inject('我是配置文件路径') envPath:string){
      const dotenv = require('dotenv')
      hashmap=dotenv.config({path})
  }
  
  get(key:string):string{
   return  this.hashmap[key]
  }
  
}

最后使用我们的动态模块

@Modules({
 imports:[动态模块]
})
class AppModules{

}

@Controller()
class AppController{

  constructor(private configservice:ConfigService){}
  
  @get('/测试配置服务')
  test(@Query('key')key:string){
    this.configservice.get(key)
  }
}