@nodescript/core
Version:
Visual programming language for Browser and Node
49 lines • 1.59 kB
JavaScript
import { parseJson } from './json.js';
export const fetchRelay = async (req, body) => {
const fetchServiceUrl = req.connectOptions?.fetchServiceUrl ?? 'https://fetch.nodescript.dev/request';
const res = await fetch(fetchServiceUrl, {
method: 'POST',
headers: makeControlHeaders(req),
body,
});
if (!res.ok) {
const responseBodyText = await res.text();
const message = (parseJson(responseBodyText, {})).message ?? responseBodyText;
throw new FetchError(`Fetch failed: ${res.status} ${message}`);
}
const status = Number(res.headers.get('x-fetch-status')) || 0;
const headers = parseJson(res.headers.get('x-fetch-headers') ?? '{}', {});
return {
status,
headers,
body: res,
};
};
function makeControlHeaders(req) {
const headers = {
'x-fetch-method': req.method,
'x-fetch-url': req.url,
'x-fetch-headers': JSON.stringify(req.headers),
'x-fetch-connect-options': JSON.stringify(req.connectOptions ?? {}),
};
if (req.proxy) {
headers['x-fetch-proxy'] = req.proxy.trim();
}
if (req.timeout != null) {
headers['x-fetch-timeout'] = String(req.timeout);
}
return headers;
}
export class FetchError extends Error {
constructor(message, code) {
super(message || code || 'Request failed');
this.name = this.constructor.name;
this.status = 500;
this.details = {};
this.details = {
code,
};
this.stack = '';
}
}
//# sourceMappingURL=fetch.js.map