dcl-catalyst-commons
Version:
Common tools and types to share between catalyst servers and clients
174 lines • 7.38 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.queryGraph = exports.postForm = exports.fetchPipe = exports.fetchBuffer = exports.fetchArrayBuffer = exports.fetchJson = exports.Fetcher = void 0;
const ms_1 = __importDefault(require("ms"));
const abort_controller_1 = __importDefault(require("abort-controller"));
const Helper_1 = require("./Helper");
const cross_fetch_1 = __importDefault(require("cross-fetch"));
const FetcherConfiguration_1 = require("./FetcherConfiguration");
/** @deprecated use well-known-components fetcher instead */
class Fetcher {
constructor(customDefaults) {
this.customDefaults = customDefaults ? customDefaults : {};
}
overrideDefaults(overrideDefaults) {
this.customDefaults = (0, Helper_1.mergeRequestOptions)(this.customDefaults, overrideDefaults);
}
fetch(url, options) {
return fetchInternal(url, {
method: 'get',
// it is better to not assume how this generic fetch will be used, not sending retries
attempts: 1,
// no timeout by default
timeout: '0s',
// no wait-time by default
waitTime: '0s',
...(0, Helper_1.mergeRequestOptions)(this.customDefaults, options)
});
}
/**
* @deprecated please use Fetcher.fetch instead
*/
fetchJson(url, options) {
return fetchJson(url, (0, Helper_1.mergeRequestOptions)(this.customDefaults, options));
}
/**
* @deprecated please use Fetcher.fetch instead
*/
fetchBuffer(url, options) {
return fetchBuffer(url, (0, Helper_1.mergeRequestOptions)(this.customDefaults, options));
}
/**
* Fetches the url and pipes the response obtained from the upstream to the `writeTo` Stream and
* returns the headers from the upstream request.
* IMPORTANT: THIS METHOD DOES NOT AWAIT THE PIPE TO FINISH. THE PROMISE FULFILLS RIGHT AFTER WE RECEIVE THE HEADERS.
* @param url to request
* @param writeTo the stream to pipe the response to
* @param options config for the request
* @deprecated please use Fetcher.fetch instead
*/
fetchPipe(url, writeTo, options) {
return fetchPipe(url, writeTo, (0, Helper_1.mergeRequestOptions)(this.customDefaults, options));
}
/**
* @deprecated please use Fetcher.fetch instead
*/
postForm(url, options) {
return postForm(url, (0, Helper_1.mergeRequestOptions)(this.customDefaults, options));
}
queryGraph(url, query, variables, options) {
return queryGraph(url, query, variables, (0, Helper_1.mergeRequestOptions)(this.customDefaults, options));
}
// Clones the fetcher and creates a new one
clone() {
return new Fetcher(this.customDefaults);
}
}
exports.Fetcher = Fetcher;
/** @deprecated use well-known-components fetcher instead */
async function fetchJson(url, options) {
const response = await fetchInternal(url, (0, Helper_1.mergeRequestOptions)(FetcherConfiguration_1.FETCH_JSON_DEFAULTS, options));
return response.json();
}
exports.fetchJson = fetchJson;
/** @deprecated use well-known-components fetcher instead */
async function fetchArrayBuffer(url, options) {
const response = await fetchInternal(url, (0, Helper_1.mergeRequestOptions)(FetcherConfiguration_1.FETCH_BUFFER_DEFAULTS, options));
return new Uint8Array(await response.arrayBuffer());
}
exports.fetchArrayBuffer = fetchArrayBuffer;
/**
* @deprecated use fetchArrayBuffer instead
*/
async function fetchBuffer(url, options) {
const response = await fetchInternal(url, (0, Helper_1.mergeRequestOptions)(FetcherConfiguration_1.FETCH_BUFFER_DEFAULTS, options));
return Buffer.from(await response.arrayBuffer());
}
exports.fetchBuffer = fetchBuffer;
/**
* Fetches the url and pipes the response obtained from the upstream to the `writeTo` Stream and
* returns the headers from the upstream request.
* IMPORTANT: THIS METHOD DOES NOT AWAIT THE PIPE TO FINISH. THE PROMISE FULFILLS RIGHT AFTER WE RECEIVE THE HEADERS.
* @param url to request
* @param writeTo the stream to pipe the response to
* @param options config for the request
* @deprecated
*/
async function fetchPipe(url, writeTo, options) {
const response = await fetchInternal(url, (0, Helper_1.mergeRequestOptions)(FetcherConfiguration_1.FETCH_BUFFER_DEFAULTS, options));
if (!response.body)
throw new Error('The function fetchPipe only works in Node.js compatible enviroments');
if ('pipe' in response.body) {
;
response.body.pipe(writeTo);
return response.headers;
}
throw new Error('The function fetchPipe only works in Node.js compatible enviroments');
}
exports.fetchPipe = fetchPipe;
async function postForm(url, options) {
const res = await fetchInternal(url, (0, Helper_1.mergeRequestOptions)(FetcherConfiguration_1.POST_DEFAULTS, options));
return res.json();
}
exports.postForm = postForm;
/** @deprecated use well-known-components thegraph-component instead */
async function queryGraph(url, query, variables, options) {
const response = (await postForm(url, {
body: JSON.stringify({ query, variables }),
headers: { 'Content-Type': 'application/json' },
...options
}));
if (response.errors) {
throw new Error(`Error querying graph. Reasons: ${JSON.stringify(response.errors)}`);
}
return response.data;
}
exports.queryGraph = queryGraph;
async function identity(a) {
return a;
}
/**
* This is the method where everything happens, all of the methods in this file call internally fetchInternal.
* If you need to modify something for all requests, do it here.
*/
async function fetchInternal(url, options) {
return (0, Helper_1.retry)(async () => {
const controller = new abort_controller_1.default();
const transformRequest = options.requestMiddleware || identity;
const transformResponse = options.responseMiddleware || identity;
const request = await transformRequest({
requestInfo: url,
requestInit: {
signal: controller.signal,
body: options.body,
method: options.method,
headers: (0, FetcherConfiguration_1.getAllHeaders)(options)
}
});
// schedule timeout right after transforming Request
const timeoutTime = (0, ms_1.default)(options.timeout);
const timeout = timeoutTime
? setTimeout(() => {
controller.abort();
}, timeoutTime)
: 0;
try {
const response = await (0, cross_fetch_1.default)(request.requestInfo, request.requestInit);
if (response.ok) {
return await transformResponse(response);
}
else {
const responseText = await response.text();
throw new Error(`Failed to fetch ${url}. Got status ${response.status}. Response was '${responseText}'`);
}
}
finally {
if (timeout)
clearTimeout(timeout);
}
}, options.attempts, options.waitTime);
}
//# sourceMappingURL=Fetcher.js.map