forked from renovatebot/renovate
/
index.ts
191 lines (170 loc) · 5.22 KB
/
index.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
import crypto from 'crypto';
import URL from 'url';
import got from 'got';
import { ExternalHostError } from '../../types/errors/external-host-error';
import * as memCache from '../cache/memory';
import { clone } from '../clone';
import { applyAuthorization, removeAuthorization } from './auth';
import { applyHostRules } from './host-rules';
interface OutgoingHttpHeaders {
[header: string]: number | string | string[] | undefined;
}
export interface HttpOptions {
body?: any;
auth?: string;
baseUrl?: string;
headers?: OutgoingHttpHeaders;
throwHttpErrors?: boolean;
useCache?: boolean;
}
export interface HttpPostOptions extends HttpOptions {
body: unknown;
}
export interface InternalHttpOptions extends HttpOptions {
json?: boolean;
method?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head';
}
export interface HttpResponse<T = string> {
body: T;
headers: any;
}
function cloneResponse<T>(response: any): HttpResponse<T> {
// clone body and headers so that the cached result doesn't get accidentally mutated
return {
body: clone<T>(response.body),
headers: clone(response.headers),
};
}
async function resolveResponse<T>(
promisedRes: Promise<HttpResponse<T>>,
{ abortOnError, abortIgnoreStatusCodes }
): Promise<HttpResponse<T>> {
try {
const res = await promisedRes;
return cloneResponse(res);
} catch (err) {
if (abortOnError && !abortIgnoreStatusCodes?.includes(err.statusCode)) {
throw new ExternalHostError(err);
}
throw err;
}
}
export class Http<GetOptions = HttpOptions, PostOptions = HttpPostOptions> {
constructor(private hostType: string, private options?: HttpOptions) {}
protected async request<T>(
requestUrl: string | URL,
httpOptions?: InternalHttpOptions
): Promise<HttpResponse<T> | null> {
let url = requestUrl.toString();
if (httpOptions?.baseUrl) {
url = URL.resolve(httpOptions.baseUrl, url);
}
// TODO: deep merge in order to merge headers
let options: any = {
method: 'get',
...this.options,
hostType: this.hostType,
...httpOptions,
};
if (process.env.NODE_ENV === 'test') {
options.retry = 0;
}
options.hooks = {
beforeRedirect: [removeAuthorization],
};
options.headers = {
...options.headers,
'user-agent':
process.env.RENOVATE_USER_AGENT ||
'https://github.com/renovatebot/renovate',
};
options = applyHostRules(url, options);
options = applyAuthorization(options);
// Cache GET requests unless useCache=false
const cacheKey = crypto
.createHash('md5')
.update('got-' + JSON.stringify({ url, headers: options.headers }))
.digest('hex');
if (options.method === 'get' && options.useCache !== false) {
// return from cache if present
const cachedRes = memCache.get(cacheKey);
// istanbul ignore if
if (cachedRes) {
return resolveResponse<T>(cachedRes, options);
}
}
const startTime = Date.now();
const promisedRes = got(url, options);
if (options.method === 'get') {
memCache.set(cacheKey, promisedRes); // always set if it's a get
}
const res = await resolveResponse<T>(promisedRes, options);
const httpRequests = memCache.get('http-requests') || [];
httpRequests.push({
method: options.method,
url,
duration: Date.now() - startTime,
});
memCache.set('http-requests', httpRequests);
return res;
}
get(url: string, options: HttpOptions = {}): Promise<HttpResponse> {
return this.request<string>(url, options);
}
head(url: string, options: HttpOptions = {}): Promise<HttpResponse> {
return this.request<string>(url, { ...options, method: 'head' });
}
private async requestJson<T = unknown>(
url: string,
options: InternalHttpOptions
): Promise<HttpResponse<T>> {
const res = await this.request<T>(url, { ...options, json: true });
const body = res.body;
return { ...res, body };
}
async getJson<T = unknown>(
url: string,
options?: GetOptions
): Promise<HttpResponse<T>> {
return this.requestJson<T>(url, { ...options });
}
async headJson<T = unknown>(
url: string,
options?: GetOptions
): Promise<HttpResponse<T>> {
return this.requestJson<T>(url, { ...options, method: 'head' });
}
async postJson<T = unknown>(
url: string,
options?: PostOptions
): Promise<HttpResponse<T>> {
return this.requestJson<T>(url, { ...options, method: 'post' });
}
async putJson<T = unknown>(
url: string,
options?: PostOptions
): Promise<HttpResponse<T>> {
return this.requestJson<T>(url, { ...options, method: 'put' });
}
async patchJson<T = unknown>(
url: string,
options?: PostOptions
): Promise<HttpResponse<T>> {
return this.requestJson<T>(url, { ...options, method: 'patch' });
}
async deleteJson<T = unknown>(
url: string,
options?: PostOptions
): Promise<HttpResponse<T>> {
return this.requestJson<T>(url, { ...options, method: 'delete' });
}
stream(url: string, options?: HttpOptions): NodeJS.ReadableStream {
const combinedOptions: any = {
method: 'get',
...this.options,
hostType: this.hostType,
...options,
};
return got.stream(url, combinedOptions);
}
}