File tree Expand file tree Collapse file tree 2 files changed +61
-1
lines changed Expand file tree Collapse file tree 2 files changed +61
-1
lines changed Original file line number Diff line number Diff line change 1- import { DynamicModule , Module , Provider } from "@nestjs/common" ;
1+ import {
2+ DynamicModule ,
3+ FactoryProvider ,
4+ Module ,
5+ ModuleMetadata ,
6+ Provider ,
7+ } from "@nestjs/common" ;
28import { HttpModule as NestHttpModule } from "@nestjs/axios" ;
39
410import { HttpService } from "./http.service" ;
@@ -83,4 +89,38 @@ export class HttpModule {
8389 provider,
8490 } ;
8591 }
92+
93+ static forFeatureAsync ( options : {
94+ serviceName : string ;
95+ imports ?: ModuleMetadata [ "imports" ] ;
96+ inject ?: FactoryProvider [ "inject" ] ;
97+ useFactory : (
98+ ...args : any [ ]
99+ ) =>
100+ | Promise < Omit < IHttpModuleOptions , "serviceName" > >
101+ | Omit < IHttpModuleOptions , "serviceName" > ;
102+ } ) : DynamicModule {
103+ const {
104+ serviceName = "HttpService" ,
105+ imports,
106+ inject,
107+ useFactory,
108+ } = options ;
109+
110+ const provider = {
111+ provide : serviceName ,
112+ useFactory : async ( ...args : any [ ] ) => {
113+ const config = await useFactory ( ...args ) ;
114+ return new HttpService ( config ) ;
115+ } ,
116+ inject : inject || [ ] ,
117+ } ;
118+
119+ return {
120+ module : HttpModule ,
121+ imports : imports || [ ] ,
122+ providers : [ provider ] ,
123+ exports : [ provider ] ,
124+ } ;
125+ }
86126}
Original file line number Diff line number Diff line change 11import { Test , TestingModule } from "@nestjs/testing" ;
2+ import { DynamicModule , FactoryProvider , ModuleMetadata } from "@nestjs/common" ;
23
34import { HttpModule } from "../http/http.module" ; // Adjust the import path as necessary
45import { HttpService } from "../http/http.service" ;
@@ -62,4 +63,23 @@ describe("HttpModule", () => {
6263 expect ( serviceOne ) . toBeInstanceOf ( HttpService ) ;
6364 expect ( serviceTwo ) . toBeInstanceOf ( HttpService ) ;
6465 } ) ;
66+
67+ it ( "should handle asynchronous dynamic configuration" , async ( ) => {
68+ const asyncConfig = {
69+ imports : [ ] as ModuleMetadata [ "imports" ] ,
70+ inject : [ ] as FactoryProvider [ "inject" ] ,
71+ useFactory : async ( ) => ( {
72+ config : { baseURL : "http://async-config.com" } ,
73+ } ) ,
74+ serviceName : "AsyncService" ,
75+ } ;
76+
77+ const asyncModule = HttpModule . forFeatureAsync ( asyncConfig ) ;
78+ const featureModule = await Test . createTestingModule ( {
79+ imports : [ asyncModule ] ,
80+ } ) . compile ( ) ;
81+ const asyncHttpService = featureModule . get < HttpService > ( "AsyncService" ) ;
82+
83+ expect ( asyncHttpService ) . toBeInstanceOf ( HttpService ) ;
84+ } ) ;
6585} ) ;
You can’t perform that action at this time.
0 commit comments