@tdb/util
Version:
Shared helpers and utilities.
105 lines • 3.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var constants_1 = require("../../constants");
var time_1 = require("../time");
var id_1 = require("../id");
if (constants_1.IS_BROWSER) {
require('whatwg-fetch');
}
var _events$ = new rxjs_1.Subject();
exports.events$ = _events$.pipe(operators_1.share());
var DEFAULT_HEADERS = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
function request(method, url, data, headers) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var timer, payload, event, ok, status, statusText, json, res, err_1, _a, error_1, response;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
timer = time_1.time.timer();
payload = {
method: method,
headers: new Headers(tslib_1.__assign({}, DEFAULT_HEADERS, (headers || {}))),
};
if (data) {
payload.body = JSON.stringify(data);
}
event = {
id: id_1.id.shortid(),
stage: 'START',
method: method,
url: url,
data: data,
headers: payload.headers,
};
_events$.next(event);
ok = true;
status = 200;
statusText = 'OK';
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4, fetch(url, payload)];
case 2:
res = _b.sent();
ok = res.ok;
status = res.status;
statusText = res.statusText;
return [3, 4];
case 3:
err_1 = _b.sent();
ok = false;
status = 521;
statusText = 'CONNECTION_REFUSED';
return [3, 4];
case 4:
_b.trys.push([4, 8, , 9]);
if (!res) return [3, 6];
return [4, res.json()];
case 5:
_a = _b.sent();
return [3, 7];
case 6:
_a = undefined;
_b.label = 7;
case 7:
json = _a;
return [3, 9];
case 8:
error_1 = _b.sent();
return [3, 9];
case 9:
response = {
ok: ok,
status: status,
statusText: statusText,
elapsed: timer.elapsed(),
data: json,
};
_events$.next(tslib_1.__assign({}, event, { stage: 'COMPLETE', response: response }));
return [2, response];
}
});
});
}
exports.request = request;
function headers(headers) {
return {
get: function (url) {
return request('GET', url, undefined, headers);
},
post: function (url, data) {
return request('POST', url, data, headers);
},
};
}
exports.headers = headers;
var DEFAULT_METHODS = headers({});
exports.get = DEFAULT_METHODS.get;
exports.post = DEFAULT_METHODS.post;
//# sourceMappingURL=http.js.map