forked from yarax/swagger-to-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-fetch.ts
50 lines (45 loc) · 1.13 KB
/
node-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
import fetch from 'node-fetch';
import { URLSearchParams } from 'url';
import { CallBackendArguments } from '../src';
function getBodyAndHeaders(
body: any,
bodyType: 'json' | 'formData',
headers: { [key: string]: string } | undefined,
) {
if (!body) {
return { headers };
}
if (bodyType === 'json') {
return {
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(body),
};
}
return {
headers,
body: new URLSearchParams(body),
};
}
export async function callBackend({
requestOptions: { method, body, baseUrl, path, query, headers, bodyType },
}: CallBackendArguments<{}>) {
const searchPath = query ? `?${new URLSearchParams(query)}` : '';
const url = `${baseUrl}${path}${searchPath}`;
const bodyAndHeaders = getBodyAndHeaders(body, bodyType, headers);
const response = await fetch(url, {
method,
...bodyAndHeaders,
});
const text = await response.text();
if (response.ok) {
try {
return JSON.parse(text);
} catch (e) {
return text;
}
}
throw new Error(`Response: ${response.status} - ${text}`);
}