Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
51 lines (45 sloc) 1.13 KB
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}`);
}
You can’t perform that action at this time.