-
Notifications
You must be signed in to change notification settings - Fork 870
/
fetch.ts
261 lines (229 loc) · 8.67 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Any modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { omitBy } from 'lodash';
import { format } from 'url';
import { BehaviorSubject } from 'rxjs';
import { isRelativeUrl, parse } from '@osd/std';
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';
interface Params {
basePath: IBasePath;
opensearchDashboardsVersion: string;
}
const JSON_CONTENT = /^(application\/(json|x-javascript)|text\/(x-)?javascript|x-json)(;.*)?$/;
const NDJSON_CONTENT = /^(application\/ndjson)(;.*)?$/;
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);
} else {
resolve(interceptedResponse.body);
}
} 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,
}),
};
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['osd-system-request'] = 'true';
}
/* `osd-version` is used on the server-side to make sure that an incoming request originated from a front-end
* of the same version; see core/server/http/lifecycle_handlers.ts
* `osd-xsrf` is to satisfy XSRF protection but is only meaningful to OpenSearch Dashboards.
*
* If the `url` equals `basePath`, starts with `basePath` + '/', or is relative, add `osd-version` and `osd-xsrf` headers.
*/
const basePath = this.params.basePath.get();
if (isRelativeUrl(url) || url === basePath || url.startsWith(`${basePath}/`)) {
fetchOptions.headers['osd-version'] = this.params.opensearchDashboardsVersion;
fetchOptions.headers['osd-xsrf'] = 'osd-fetch';
}
return new Request(url, fetchOptions as RequestInit);
}
private async fetchResponse(fetchOptions: HttpFetchOptionsWithPath): Promise<HttpResponse<any>> {
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)) {
body = await response.blob();
} else if (JSON_CONTENT.test(contentType)) {
// ToDo: [3.x] Remove withLongNumerals
body =
fetchOptions.withLongNumeralsSupport || fetchOptions.withLongNumerals
? parse(await response.text())
: await response.json();
} else {
const text = await response.text();
try {
// ToDo: [3.x] Remove withLongNumerals
body =
fetchOptions.withLongNumeralsSupport || fetchOptions.withLongNumerals
? parse(text)
: 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 (pathOrOptions: string | HttpFetchOptionsWithPath, options?: HttpFetchOptions) => {
const optionsWithPath = validateFetchArguments(pathOrOptions, options);
return this.fetch({ ...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('osd-')
);
if (invalidHeaders.length) {
throw new Error(
`Invalid fetch headers, headers beginning with "osd-" are not allowed: [${invalidHeaders.join(
','
)}]`
);
}
return fullOptions;
};