generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
sendRequest.ts
59 lines (52 loc) · 2 KB
/
sendRequest.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
import request, {CoreOptions, Response} from "request";
import {RawRequest} from "./request";
import {AccessHeaders} from "./ts-rest-client";
export const CallIdHeader = 'x-callid';
export interface RequestOptions {
proxy?: string;
ignoreCertError?: boolean;
log(msg: string, ...args: any[]);
}
export function sendRequest<T>(req: RawRequest, options: RequestOptions) {
const start = Date.now();
const reqOptions: CoreOptions = {
headers: {...req.headers, ['Content-type']: 'application/json'},
body: req.body,
// ca: ''
};
if (options.ignoreCertError) {
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0 as any; // todo: restore it?
}
if (options.proxy) {
options.log(`sending via proxy:`, options.proxy);
reqOptions.proxy = options.proxy;
reqOptions.tunnel = false;
}
return new Promise<T>((resolve, reject) => request[req.method](
req.uri, reqOptions, (error: any, response: Response, body: string) => {
options.log(`request to ${req.method.toUpperCase()} ${req.uri} took ${(Date.now() - start) / 1000} seconds`);
if (error) {
options.log(`error:`, error, response, body);
reject({
errorCode: error.errno ?? 'unknown',
errorDetails: error.syscall == 'getaddrinfo' ? 'missing vpn connection?' : error,
});
return;
}
try {
options.log(body);
resolve(
Object.assign(JSON.parse(body),
{
[AccessHeaders]: response.headers,
[CallIdHeader]: response.headers[CallIdHeader]?.toString()
}
)
);
} catch (ex) {
options.log(`failed to parse response body from request to ${req.uri}\n${body}`);
reject({error: ex, body});
}
})
);
}