Skip to content

Commit 8fd8110

Browse files
Ashish KumarAshish Kumar
authored andcommitted
chore: added support for forFeatureAsync
1 parent 9ba15fc commit 8fd8110

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

src/http/http.module.ts

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { DynamicModule, Module, Provider } from "@nestjs/common";
1+
import {
2+
DynamicModule,
3+
FactoryProvider,
4+
Module,
5+
ModuleMetadata,
6+
Provider,
7+
} from "@nestjs/common";
28
import { HttpModule as NestHttpModule } from "@nestjs/axios";
39

410
import { 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
}

src/test/HttpModule.spec.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Test, TestingModule } from "@nestjs/testing";
2+
import { DynamicModule, FactoryProvider, ModuleMetadata } from "@nestjs/common";
23

34
import { HttpModule } from "../http/http.module"; // Adjust the import path as necessary
45
import { 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
});

0 commit comments

Comments
 (0)