-
Notifications
You must be signed in to change notification settings - Fork 257
/
fetchRequest.ts
84 lines (76 loc) · 2.66 KB
/
fetchRequest.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
/*!
* Copyright (c) 2018-present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 crossFetch from 'cross-fetch';
import { FetchOptions, FetchResponse, HttpResponse } from '../types';
function readData(response: FetchResponse): Promise<object | string> {
if (response.headers.get('Content-Type') &&
response.headers.get('Content-Type').toLowerCase().indexOf('application/json') >= 0) {
return response.json()
// JSON parse can fail if response is not a valid object
.catch(e => {
return {
error: e,
errorSummary: 'Could not parse server response'
};
});
} else {
return response.text();
}
}
function formatResult(status: number, data: object | string) {
const isObject = typeof data === 'object';
const result: HttpResponse = {
responseText: isObject ? JSON.stringify(data) : data as string,
status: status
};
if (isObject) {
result.responseType = 'json';
result.responseJSON = data as object;
}
return result;
}
/* eslint-disable complexity */
function fetchRequest(method: string, url: string, args: FetchOptions) {
var body = args.data;
var headers = args.headers || {};
var contentType = (headers['Content-Type'] || headers['content-type'] || '');
// JSON encode body (if appropriate)
if (contentType === 'application/json' && body && typeof body !== 'string') {
body = JSON.stringify(body);
}
var fetch = global.fetch || crossFetch;
var fetchPromise = fetch(url, {
method: method,
headers: args.headers,
body: body as string,
credentials: args.withCredentials ? 'include' : 'omit'
});
if (!fetchPromise.finally) {
fetchPromise = Promise.resolve(fetchPromise);
}
return fetchPromise.then(function(response) {
var error = !response.ok;
var status = response.status;
return readData(response)
.then(data => {
return formatResult(status, data);
})
.then(result => {
if (error || result.responseJSON?.error) {
// Throwing result object since error handling is done in http.js
throw result;
}
return result;
});
});
}
export default fetchRequest;