-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathhttp-client.ts
211 lines (195 loc) · 6.81 KB
/
http-client.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import * as http from 'http';
import * as https from 'https';
import { createLogger, ErrorWithCause } from '@sap-cloud-sdk/util';
import axios, { AxiosRequestConfig } from 'axios';
import {
buildHeadersForDestination,
Destination,
DestinationNameAndJwt,
toDestinationNameUrl,
useOrFetchDestination
} from '../connectivity/scp-cf';
import { getAgentConfig } from './http-agent';
import {
DestinationHttpRequestConfig,
ExecuteHttpRequestFn,
HttpRequest,
HttpRequestConfig,
HttpResponse
} from './http-client-types';
const logger = createLogger({
package: 'core',
messageContext: 'http-client'
});
/**
* Builds a [[DestinationHttpRequestConfig]] for the given destination.
* If a destination name (and a JWT) are provided, it will try to resolve the destination.
*
* @param destination - A destination or a destination name and a JWT.
* @param customHeaders - Custom default headers for the resulting HTTP request.
* @returns A [[DestinationHttpRequestConfig]].
*/
export async function buildHttpRequest(
destination: Destination | DestinationNameAndJwt,
customHeaders?: Record<string, any>
): Promise<DestinationHttpRequestConfig> {
if (customHeaders) {
logger.warn(
`The custom headers are provided with the keys: ${Object.keys(
customHeaders
)}. These keys will overwrite the headers created by the SDK.`
);
}
const resolvedDestination = await resolveDestination(destination);
if (!resolvedDestination) {
throw Error(
`Failed to resolve the destination: ${toDestinationNameUrl(destination)}.`
);
}
const headers = await buildHeaders(resolvedDestination, customHeaders);
return buildDestinationHttpRequestConfig(resolvedDestination, headers);
}
/**
* Builds a [[DestinationHttpRequestConfig]] for the given destination
* and then merges it into the given request configuration.
* Setting of the given request configuration take precedence over any destination related configuration.
*
* @param destination - A destination or a destination name and a JWT.
* @param requestConfig - Any object representing an HTTP request.
* @returns The given request config merged with the config built for the given destination.
*/
export function addDestinationToRequestConfig<T extends HttpRequestConfig>(
destination: Destination | DestinationNameAndJwt,
requestConfig: T
): Promise<T & DestinationHttpRequestConfig> {
return buildHttpRequest(destination).then(destinationConfig =>
merge(destinationConfig, requestConfig)
);
}
/**
* Takes as paramter a function that expects an [[HttpRequest]] and returns a Promise of [[HttpResponse]].
* Returns a function that takes a destination and a request-config (extends [[HttpRequestConfig]]), builds an [[HttpRequest]] from them, and calls
* the provided execute function.
*
* NOTE: If you simply want to execute a request without passing your own execute function, use [[executeHttpRequest]] instead!
*
* @param executeFn - A function that can execute an [[HttpRequestConfig]].
* @returns A function expecting destination and a request.
*/
export function execute(executeFn: ExecuteHttpRequestFn) {
return async function <T extends HttpRequestConfig>(
destination: Destination | DestinationNameAndJwt,
requestConfig: T
): Promise<HttpResponse> {
const destinationRequestConfig = await buildHttpRequest(
destination,
requestConfig.headers
);
const request = merge(destinationRequestConfig, requestConfig);
return executeFn(request);
};
}
/**
*
* @experimental This API is experimental and might change in newer versions. Use with caution.
* @param destination - A destination or a destination name and a JWT.
* @param requestConfig - Any object representing an HTTP request.
*/
export async function buildAxiosRequestConfig<T extends HttpRequestConfig>(
destination: Destination | DestinationNameAndJwt,
requestConfig?: Partial<T>
): Promise<AxiosRequestConfig> {
const destinationRequestConfig = await buildHttpRequest(
destination,
requestConfig?.headers
);
const request = requestConfig
? merge(destinationRequestConfig, requestConfig)
: destinationRequestConfig;
return { ...getAxiosConfigWithDefaultsWithoutMethod(), ...request };
}
/**
* Builds a [[DestinationHttpRequestConfig]] for the given destination, merges it into the given requestConfig
* and executes it (using Axios).
*
* @param destination - A destination or a destination name and a JWT.
* @param requestConfig - Any object representing an HTTP request.
* @returns An [[HttpResponse]].
*/
export const executeHttpRequest = execute(executeWithAxios);
function buildDestinationHttpRequestConfig(
destination: Destination,
headers: Record<string, string>
): DestinationHttpRequestConfig {
return {
baseURL: destination.url,
headers,
...getAgentConfig(destination)
};
}
function buildHeaders(
destination: Destination,
customHeaders?: Record<string, any>
): Promise<Record<string, string>> {
return buildHeadersForDestination(destination, customHeaders).catch(error => {
throw new ErrorWithCause(
'Failed to build HTTP request for destination: failed to build headers!',
error
);
});
}
function resolveDestination(
destination: Destination | DestinationNameAndJwt
): Promise<Destination | null> {
return useOrFetchDestination(destination).catch(error => {
throw new ErrorWithCause(
'Failed to build HTTP request for destination: failed to load destination!',
error
);
});
}
function merge<T extends HttpRequestConfig>(
destinationRequestConfig: DestinationHttpRequestConfig,
customRequestConfig: T
): T & DestinationHttpRequestConfig;
function merge<T extends HttpRequestConfig>(
destinationRequestConfig: DestinationHttpRequestConfig,
customRequestConfig: Partial<T>
): Partial<T> & DestinationHttpRequestConfig;
function merge<T extends HttpRequestConfig>(
destinationRequestConfig: DestinationHttpRequestConfig,
customRequestConfig: T | Partial<T>
): (T | Partial<T>) & DestinationHttpRequestConfig {
return {
...destinationRequestConfig,
...customRequestConfig,
headers: {
...destinationRequestConfig.headers,
...customRequestConfig.headers
}
};
}
function executeWithAxios(request: HttpRequest): Promise<HttpResponse> {
return axios.request({ ...getAxiosConfigWithDefaults(), ...request });
}
/**
* Builds an Axios config with default configuration i.e. no_proxy, default http and https agent and GET as request method.
*
* @returns AxiosRequestConfig with default parameters
*/
export function getAxiosConfigWithDefaults(): HttpRequestConfig {
return {
...getAxiosConfigWithDefaultsWithoutMethod(),
method: 'get'
};
}
export function getAxiosConfigWithDefaultsWithoutMethod(): Omit<
HttpRequestConfig,
'method'
> {
return {
proxy: false,
httpAgent: new http.Agent(),
httpsAgent: new https.Agent()
};
}