forked from nest-cloud/nestcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.module.ts
68 lines (60 loc) · 2.43 KB
/
http.module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Module, DynamicModule, Global } from '@nestjs/common';
import { HTTP, BOOT, CONFIG, IBoot, IConfig, Scanner } from '@nestcloud/common';
import { AsyncHttpOptions, HttpOptions } from './interfaces/http-options.interface';
import { AXIOS_INSTANCE_PROVIDER, HTTP_OPTIONS_PROVIDER } from './http.constants';
import axios from 'axios';
import { DiscoveryModule } from '@nestjs/core';
import { HttpOrchestrator } from './http.orchestrator';
import { HttpMetadataAccessor } from './http-metadata.accessor';
import { HttpExplorer } from './http.explorer';
import { HttpClient } from './http.client';
@Global()
@Module({
imports: [DiscoveryModule],
providers: [HttpOrchestrator, HttpMetadataAccessor, Scanner],
})
export class HttpModule {
private static readonly CONFIG_PREFIX = 'http';
public static forRoot(options: HttpOptions = {}): DynamicModule {
return this.register(options);
}
public static forRootAsync(options: AsyncHttpOptions): DynamicModule {
return this.register(options);
}
private static register(options: HttpOptions & AsyncHttpOptions = {}): DynamicModule {
const inject = options.inject || [];
const httpOptionsProvider = {
provide: HTTP_OPTIONS_PROVIDER,
useFactory: (...params: any[]) => {
let registerOptions = options;
const boot: IBoot = params[inject.indexOf(BOOT)];
if (boot) {
options = boot.get<HttpOptions>(this.CONFIG_PREFIX);
registerOptions = Object.assign(registerOptions, options);
}
const config: IConfig = params[inject.indexOf(CONFIG)];
if (config) {
options = config.get<HttpOptions>(this.CONFIG_PREFIX);
}
return Object.assign(registerOptions, options);
},
inject,
};
const axiosProvider = {
provide: AXIOS_INSTANCE_PROVIDER,
useFactory: () => axios,
};
const httpProvider = {
provide: HTTP,
useFactory: async (httpClient: HttpClient): Promise<any> => {
return httpClient;
},
inject: [HttpClient],
};
return {
module: HttpModule,
providers: [httpProvider, httpOptionsProvider, axiosProvider, HttpExplorer, HttpClient],
exports: [httpProvider],
};
}
}