-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathmakeRequest.ts
More file actions
338 lines (304 loc) · 10 KB
/
makeRequest.ts
File metadata and controls
338 lines (304 loc) · 10 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/* ============================================================================
* Copyright (c) Palo Alto Networks
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* ========================================================================== */
import { Body } from "@theme/ApiExplorer/Body/slice";
import * as sdk from "postman-collection";
// Custom error types for better error handling
export type RequestErrorType =
| "timeout"
| "network"
| "cors"
| "abort"
| "unknown";
export class RequestError extends Error {
type: RequestErrorType;
originalError?: Error;
constructor(type: RequestErrorType, message: string, originalError?: Error) {
super(message);
this.name = "RequestError";
this.type = type;
this.originalError = originalError;
}
}
const DEFAULT_REQUEST_TIMEOUT = 30000; // 30 seconds
function fetchWithtimeout(
url: string,
options: RequestInit,
timeout = DEFAULT_REQUEST_TIMEOUT
): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
return fetch(url, {
...options,
signal: controller.signal,
})
.then((response) => {
clearTimeout(timeoutId);
return response;
})
.catch((error) => {
clearTimeout(timeoutId);
// Check if it was an abort due to timeout
if (error.name === "AbortError") {
throw new RequestError(
"timeout",
"The request timed out waiting for the server to respond. Please try again. If the issue persists, try using a different client (e.g., curl) with a longer timeout.",
error
);
}
// Check for network errors (offline, DNS failure, etc.)
if (error instanceof TypeError && error.message === "Failed to fetch") {
// This could be CORS, network failure, or the server being unreachable
throw new RequestError(
"network",
"Unable to reach the server. Please check your network connection and verify the server URL is correct. If the server is running, this may be a CORS issue.",
error
);
}
// Handle other TypeErrors that might indicate CORS issues
if (error instanceof TypeError) {
throw new RequestError(
"cors",
"The request was blocked, possibly due to CORS restrictions. Ensure the server allows requests from this origin, or try using a proxy.",
error
);
}
// Generic error fallback
throw new RequestError(
"unknown",
error.message ||
"An unexpected error occurred while making the request.",
error
);
});
}
async function loadImage(content: Blob): Promise<string | ArrayBuffer | null> {
return new Promise((accept, reject) => {
const reader = new FileReader();
reader.onabort = () => {
console.log("file reading was aborted");
reject();
};
reader.onerror = () => {
console.log("file reading has failed");
reject();
};
reader.onload = () => {
// Do whatever you want with the file contents
const binaryStr = reader.result;
accept(binaryStr);
};
reader.readAsArrayBuffer(content);
});
}
async function makeRequest(
request: sdk.Request,
proxy: string | undefined,
_body: Body,
timeout: number = DEFAULT_REQUEST_TIMEOUT,
credentials?: RequestCredentials
) {
const headers = request.toJSON().header;
let myHeaders = new Headers();
if (headers) {
headers.forEach((header: any) => {
if (header.key && header.value) {
myHeaders.append(header.key, header.value);
}
});
}
// The following code handles multiple files in the same formdata param.
// It removes the form data params where the src property is an array of filepath strings
// Splits that array into different form data params with src set as a single filepath string
// TODO:
// if (request.body && request.body.mode === 'formdata') {
// let formdata = request.body.formdata,
// formdataArray = [];
// formdata.members.forEach((param) => {
// let key = param.key,
// type = param.type,
// disabled = param.disabled,
// contentType = param.contentType;
// // check if type is file or text
// if (type === 'file') {
// // if src is not of type string we check for array(multiple files)
// if (typeof param.src !== 'string') {
// // if src is an array(not empty), iterate over it and add files as separate form fields
// if (Array.isArray(param.src) && param.src.length) {
// param.src.forEach((filePath) => {
// addFormParam(
// formdataArray,
// key,
// param.type,
// filePath,
// disabled,
// contentType
// );
// });
// }
// // if src is not an array or string, or is an empty array, add a placeholder for file path(no files case)
// else {
// addFormParam(
// formdataArray,
// key,
// param.type,
// '/path/to/file',
// disabled,
// contentType
// );
// }
// }
// // if src is string, directly add the param with src as filepath
// else {
// addFormParam(
// formdataArray,
// key,
// param.type,
// param.src,
// disabled,
// contentType
// );
// }
// }
// // if type is text, directly add it to formdata array
// else {
// addFormParam(
// formdataArray,
// key,
// param.type,
// param.value,
// disabled,
// contentType
// );
// }
// });
// request.body.update({
// mode: 'formdata',
// formdata: formdataArray,
// });
// }
const body = request.body?.toJSON();
let myBody: RequestInit["body"] = undefined;
if (body !== undefined && Object.keys(body).length > 0) {
switch (body.mode) {
case "urlencoded": {
myBody = new URLSearchParams();
if (Array.isArray(body.urlencoded)) {
for (const data of body.urlencoded) {
if (data.key && data.value) {
myBody.append(data.key, data.value);
}
}
}
break;
}
case "raw": {
myBody = (body.raw ?? "").toString();
break;
}
case "formdata": {
// The Content-Type header will be set automatically based on the type of body.
myHeaders.delete("Content-Type");
myBody = new FormData();
const members = (request.body as any)?.formdata?.members;
if (Array.isArray(members)) {
for (const data of members) {
if (data.key && data.value.content) {
myBody.append(data.key, data.value.content);
}
// handle generic key-value payload
if (data.key && typeof data.value === "string") {
myBody.append(data.key, data.value);
}
}
}
break;
}
case "file": {
if (_body.type === "raw" && _body.content?.type === "file") {
myBody = await loadImage(_body.content.value.content);
}
break;
}
default:
break;
}
}
const requestOptions: RequestInit = {
method: request.method,
headers: myHeaders,
body: myBody,
...(credentials && { credentials }),
};
let finalUrl = request.url.toString();
if (proxy) {
// Ensure the proxy ends with a slash.
let normalizedProxy = proxy.replace(/\/$/, "") + "/";
finalUrl = normalizedProxy + request.url.toString();
}
try {
const response = await fetchWithtimeout(finalUrl, requestOptions, timeout);
const contentType = response.headers.get("content-type");
let fileExtension = "";
if (contentType) {
if (contentType.includes("application/pdf")) {
fileExtension = ".pdf";
} else if (contentType.includes("image/jpeg")) {
fileExtension = ".jpg";
} else if (contentType.includes("image/png")) {
fileExtension = ".png";
} else if (contentType.includes("image/gif")) {
fileExtension = ".gif";
} else if (contentType.includes("image/webp")) {
fileExtension = ".webp";
} else if (contentType.includes("video/mpeg")) {
fileExtension = ".mpeg";
} else if (contentType.includes("video/mp4")) {
fileExtension = ".mp4";
} else if (contentType.includes("audio/mpeg")) {
fileExtension = ".mp3";
} else if (contentType.includes("audio/ogg")) {
fileExtension = ".ogg";
} else if (contentType.includes("application/octet-stream")) {
fileExtension = ".bin";
} else if (contentType.includes("application/zip")) {
fileExtension = ".zip";
}
if (fileExtension) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
// Now the file name includes the extension
link.setAttribute("download", `file${fileExtension}`);
// These two lines are necessary to make the link click in Firefox
link.style.display = "none";
document.body.appendChild(link);
link.click();
// After link is clicked, it's safe to remove it.
setTimeout(() => document.body.removeChild(link), 0);
return response;
} else {
return response;
}
}
return response;
} catch (error) {
// Re-throw RequestError instances as-is
if (error instanceof RequestError) {
throw error;
}
// Wrap unexpected errors
throw new RequestError(
"unknown",
error instanceof Error
? error.message
: "An unexpected error occurred while processing the response.",
error instanceof Error ? error : undefined
);
}
}
export default makeRequest;