-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathfetch.ts
230 lines (200 loc) · 7.28 KB
/
fetch.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { omitBy } from 'lodash';
import { format } from 'url';
import { BehaviorSubject } from 'rxjs';
import {
IBasePath,
HttpInterceptor,
HttpHandler,
HttpFetchOptions,
HttpResponse,
HttpFetchOptionsWithPath,
} from './types';
import { HttpFetchError } from './http_fetch_error';
import { HttpInterceptController } from './http_intercept_controller';
import { interceptRequest, interceptResponse } from './intercept';
import { HttpInterceptHaltError } from './http_intercept_halt_error';
import { ExecutionContextContainer } from '../execution_context';
interface Params {
basePath: IBasePath;
kibanaVersion: string;
}
const JSON_CONTENT = /^(application\/(json|x-javascript)|text\/(x-)?javascript|x-json)(;.*)?$/;
const NDJSON_CONTENT = /^(application\/ndjson)(;.*)?$/;
const ZIP_CONTENT = /^(application\/zip)(;.*)?$/;
const removedUndefined = (obj: Record<string, any> | undefined) => {
return omitBy(obj, (v) => v === undefined);
};
export class Fetch {
private readonly interceptors = new Set<HttpInterceptor>();
private readonly requestCount$ = new BehaviorSubject(0);
constructor(private readonly params: Params) {}
public intercept(interceptor: HttpInterceptor) {
this.interceptors.add(interceptor);
return () => {
this.interceptors.delete(interceptor);
};
}
public removeAllInterceptors() {
this.interceptors.clear();
}
public getRequestCount$() {
return this.requestCount$.asObservable();
}
public readonly delete = this.shorthand('DELETE');
public readonly get = this.shorthand('GET');
public readonly head = this.shorthand('HEAD');
public readonly options = this.shorthand('options');
public readonly patch = this.shorthand('PATCH');
public readonly post = this.shorthand('POST');
public readonly put = this.shorthand('PUT');
public fetch: HttpHandler = async <TResponseBody>(
pathOrOptions: string | HttpFetchOptionsWithPath,
options?: HttpFetchOptions
) => {
const optionsWithPath = validateFetchArguments(pathOrOptions, options);
const controller = new HttpInterceptController();
// We wrap the interception in a separate promise to ensure that when
// a halt is called we do not resolve or reject, halting handling of the promise.
return new Promise<TResponseBody | HttpResponse<TResponseBody>>(async (resolve, reject) => {
try {
this.requestCount$.next(this.requestCount$.value + 1);
const interceptedOptions = await interceptRequest(
optionsWithPath,
this.interceptors,
controller
);
const initialResponse = this.fetchResponse(interceptedOptions);
const interceptedResponse = await interceptResponse(
interceptedOptions,
initialResponse,
this.interceptors,
controller
);
if (optionsWithPath.asResponse) {
resolve(interceptedResponse as HttpResponse<TResponseBody>);
} else {
resolve(interceptedResponse.body as TResponseBody);
}
} catch (error) {
if (!(error instanceof HttpInterceptHaltError)) {
reject(error);
}
} finally {
this.requestCount$.next(this.requestCount$.value - 1);
}
});
};
private createRequest(options: HttpFetchOptionsWithPath): Request {
// Merge and destructure options out that are not applicable to the Fetch API.
const {
query,
prependBasePath: shouldPrependBasePath,
asResponse,
asSystemRequest,
...fetchOptions
} = {
method: 'GET',
credentials: 'same-origin',
prependBasePath: true,
...options,
// options can pass an `undefined` Content-Type to erase the default value.
// however we can't pass it to `fetch` as it will send an `Content-Type: Undefined` header
headers: removedUndefined({
'Content-Type': 'application/json',
...options.headers,
'kbn-version': this.params.kibanaVersion,
...(options.context ? new ExecutionContextContainer(options.context).toHeader() : {}),
}),
};
const url = format({
pathname: shouldPrependBasePath ? this.params.basePath.prepend(options.path) : options.path,
query: removedUndefined(query),
});
// Make sure the system request header is only present if `asSystemRequest` is true.
if (asSystemRequest) {
fetchOptions.headers['kbn-system-request'] = 'true';
}
return new Request(url, fetchOptions as RequestInit);
}
private async fetchResponse(
fetchOptions: HttpFetchOptionsWithPath
): Promise<HttpResponse<unknown>> {
const request = this.createRequest(fetchOptions);
let response: Response;
let body = null;
try {
response = await window.fetch(request);
} catch (err) {
throw new HttpFetchError(err.message, err.name ?? 'Error', request);
}
const contentType = response.headers.get('Content-Type') || '';
try {
if (NDJSON_CONTENT.test(contentType) || ZIP_CONTENT.test(contentType)) {
body = await response.blob();
} else if (JSON_CONTENT.test(contentType)) {
body = await response.json();
} else {
const text = await response.text();
try {
body = JSON.parse(text);
} catch (err) {
body = text;
}
}
} catch (err) {
throw new HttpFetchError(err.message, err.name ?? 'Error', request, response, body);
}
if (!response.ok) {
throw new HttpFetchError(response.statusText, 'Error', request, response, body);
}
return { fetchOptions, request, response, body };
}
private shorthand(method: string): HttpHandler {
return <T = unknown>(
pathOrOptions: string | HttpFetchOptionsWithPath,
options?: HttpFetchOptions
) => {
const optionsWithPath: HttpFetchOptionsWithPath = validateFetchArguments(
pathOrOptions,
options
);
return this.fetch<HttpResponse<T>>({ ...optionsWithPath, method });
};
}
}
/**
* Ensure that the overloaded arguments to `HttpHandler` are valid.
*/
const validateFetchArguments = (
pathOrOptions: string | HttpFetchOptionsWithPath,
options?: HttpFetchOptions
): HttpFetchOptionsWithPath => {
let fullOptions: HttpFetchOptionsWithPath;
if (typeof pathOrOptions === 'string' && (typeof options === 'object' || options === undefined)) {
fullOptions = { ...options, path: pathOrOptions };
} else if (typeof pathOrOptions === 'object' && options === undefined) {
fullOptions = pathOrOptions;
} else {
throw new Error(
`Invalid fetch arguments, must either be (string, object) or (object, undefined), received (${typeof pathOrOptions}, ${typeof options})`
);
}
const invalidHeaders = Object.keys(fullOptions.headers ?? {}).filter((headerName) =>
headerName.startsWith('kbn-')
);
if (invalidHeaders.length) {
throw new Error(
`Invalid fetch headers, headers beginning with "kbn-" are not allowed: [${invalidHeaders.join(
','
)}]`
);
}
return fullOptions;
};