1- import Axios , { AxiosRequestConfig } from 'axios' ;
1+ import Axios from 'axios' ;
22import { Module } from '../decorators/modules/module.decorator' ;
3- import { DynamicModule } from '../interfaces' ;
3+ import { DynamicModule , Provider } from '../interfaces' ;
44import { randomStringGenerator } from '../utils/random-string-generator.util' ;
5- import { AXIOS_INSTANCE_TOKEN , HTTP_MODULE_ID } from './http.constants' ;
5+ import {
6+ AXIOS_INSTANCE_TOKEN ,
7+ HTTP_MODULE_ID ,
8+ HTTP_MODULE_OPTIONS ,
9+ } from './http.constants' ;
610import { HttpService } from './http.service' ;
11+ import {
12+ HttpModuleAsyncOptions ,
13+ HttpModuleOptions ,
14+ HttpModuleOptionsFactory ,
15+ } from './interfaces' ;
716
817@Module ( {
918 providers : [
@@ -16,7 +25,7 @@ import { HttpService } from './http.service';
1625 exports : [ HttpService ] ,
1726} )
1827export class HttpModule {
19- static register ( config : AxiosRequestConfig ) : DynamicModule {
28+ static register ( config : HttpModuleOptions ) : DynamicModule {
2029 return {
2130 module : HttpModule ,
2231 providers : [
@@ -31,4 +40,52 @@ export class HttpModule {
3140 ] ,
3241 } ;
3342 }
43+
44+ static registerAsync ( options : HttpModuleAsyncOptions ) : DynamicModule {
45+ return {
46+ module : HttpModule ,
47+ imports : options . imports ,
48+ providers : [
49+ ...this . createAsyncProviders ( options ) ,
50+ {
51+ provide : HTTP_MODULE_ID ,
52+ useValue : randomStringGenerator ( ) ,
53+ } ,
54+ ...( options . extraProviders || [ ] ) ,
55+ ] ,
56+ } ;
57+ }
58+
59+ private static createAsyncProviders (
60+ options : HttpModuleAsyncOptions ,
61+ ) : Provider [ ] {
62+ if ( options . useExisting || options . useFactory ) {
63+ return [ this . createAsyncOptionsProvider ( options ) ] ;
64+ }
65+ return [
66+ this . createAsyncOptionsProvider ( options ) ,
67+ {
68+ provide : options . useClass ,
69+ useClass : options . useClass ,
70+ } ,
71+ ] ;
72+ }
73+
74+ private static createAsyncOptionsProvider (
75+ options : HttpModuleAsyncOptions ,
76+ ) : Provider {
77+ if ( options . useFactory ) {
78+ return {
79+ provide : HTTP_MODULE_OPTIONS ,
80+ useFactory : options . useFactory ,
81+ inject : options . inject || [ ] ,
82+ } ;
83+ }
84+ return {
85+ provide : HTTP_MODULE_OPTIONS ,
86+ useFactory : async ( optionsFactory : HttpModuleOptionsFactory ) =>
87+ optionsFactory . createHttpOptions ( ) ,
88+ inject : [ options . useExisting || options . useClass ] ,
89+ } ;
90+ }
3491}
0 commit comments