"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_1 = require("graphql");
var httpObservable_1 = require("./httpObservable");
var fetcherUtils_1 = require("./fetcherUtils");
require("isomorphic-fetch");
var DEFAULT_BATCH = 0;
var BatchHttpFetcher = (function () {
function BatchHttpFetcher(fetchParams) {
this._fetch = fetchParams && fetchParams.fetch;
this._uri = fetchParams && fetchParams.uri ? fetchParams.uri : '';
this.batchInterval = fetchParams && fetchParams.batchInterval ? fetchParams.batchInterval : DEFAULT_BATCH;
this.outstandingRequests = [];
this.startedInterval = false;
this.sendBatch = this.sendBatch.bind(this);
}
BatchHttpFetcher.prototype.request = function (operation) {
var _this = this;
fetcherUtils_1.validateOperation(operation);
var observable = new httpObservable_1.default(new Promise(function (resolve, reject) {
_this.outstandingRequests.push({ operation: operation, resolve: resolve, reject: reject });
}));
if (!this.startedInterval) {
this.startedInterval = true;
setTimeout(this.sendBatch, this.batchInterval);
}
return observable;
};
BatchHttpFetcher.prototype.printRequest = function (operation) {
return __assign({}, operation, { query: graphql_1.print(operation.query) });
};
BatchHttpFetcher.prototype.sendBatch = function () {
var _this = this;
var requestsToService = this.outstandingRequests;
this.outstandingRequests = [];
var printedRequests = requestsToService.map(function (request) {
return _this.printRequest(request.operation);
});
var options = {
method: 'POST',
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
},
body: JSON.stringify(printedRequests),
};
var batchedResults = this._fetch ? this._fetch(this._uri, options) : fetch(this._uri, options);
batchedResults.then(function (res) { return res.json(); })
.then((function (results) {
results.forEach(function (result, i) { return requestsToService[i].resolve(result); });
}))
.catch(function (error) {
requestsToService.forEach(function (request) { return request.reject(error); });
});
this.startedInterval = false;
};
return BatchHttpFetcher;
}());
exports.default = BatchHttpFetcher;
//# sourceMappingURL=batchHttpFetcher.js.map |