-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-request.ts
executable file
·81 lines (80 loc) · 2.62 KB
/
api-request.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
/**
* @license
* Copyright FabricElements. All Rights Reserved.
*/
import fetch from 'node-fetch';
import type {InterfaceAPIRequest} from './interfaces.js';
/**
* Call firebase project base API
* @param {InterfaceAPIRequest} options
*/
export default async (options: InterfaceAPIRequest) => {
if (!options.path) {
throw new Error('Invalid api call');
}
const finalBody = JSON.stringify(options.body);
const requestOptions: any = {
method: options.method,
// 'Content-Type': 'application/json',
headers: options.headers ?? {},
// can be null, a string, a Buffer, a Blob, or a Node.js Readable stream
body: finalBody,
// set to `manual` to extract redirect headers, `error` to reject redirect
redirect: 'error',
// The following properties are node-fetch extensions
// maximum redirect count. 0 to not follow redirect
follow: 2,
// req/res timeout in ms, it resets on redirect. 0 to disable.
timeout: 60000,
// Signal is recommended instead.
size: 0, // maximum response body size in bytes. 0 to disable
// http(s).Agent instance, allows custom proxy, certificate, dns lookup etc.
agent: null,
compress: true,
};
if (options.scheme && options.credentials) {
requestOptions.headers.Authorization = `${options.scheme} ${options.credentials}`;
}
const response = await fetch(options.path, requestOptions);
let responseData = null;
if (!response.ok) {
const BodyJsonError = await response.json();
// noinspection ExceptionCaughtLocallyJS
throw new Error(Object.prototype.hasOwnProperty.call(BodyJsonError, 'message') ? BodyJsonError['message'] : 'unknown error');
}
console.log('content-type', response.headers.get('content-type'));
switch (options.as) {
case 'arrayBuffer':
responseData = await response.arrayBuffer();
break;
case 'formData':
responseData = await response.formData();
break;
case 'blob':
responseData = await response.blob();
break;
case 'json':
responseData = await response.json();
break;
case 'text':
responseData = await response.text();
break;
case 'raw':
responseData = response.body;
break;
default:
// Return response depending on the content-type
switch (response.headers.get('content-type')?.toString().toLowerCase()) {
case 'text/plain':
case 'text/html':
responseData = await response.text();
break;
case 'application/json':
responseData = await response.json();
break;
default:
responseData = response.body;
}
}
return responseData;
};