@nu-art/thunder
Version:
Thunder - React & Typescript based frontend framework
343 lines • 14.6 kB
JavaScript
"use strict";
/*
* Thunder is a typescript & react frontend foundation that natively
* runs on firebase function and is a part of the Thunderstorm larger project
*
* Copyright (C) 2018 Adam van der Kruk aka TacB0sS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var ts_common_1 = require("@nu-art/ts-common");
var http_module_1 = require("./http-module");
var zlib_1 = require("zlib");
var HttpException = /** @class */ (function (_super) {
__extends(HttpException, _super);
function HttpException(responseCode, url) {
return _super.call(this, responseCode + " - " + url) || this;
}
return HttpException;
}(Error));
exports.HttpException = HttpException;
var HttpRequest = /** @class */ (function () {
function HttpRequest(requestKey, requestData) {
this.headers = {};
this.method = ts_common_1.HttpMethod.GET;
this.timeout = 10000;
this.params = {};
this.handleRequestSuccess = http_module_1.HttpModule.handleRequestSuccess;
this.handleRequestFailure = http_module_1.HttpModule.handleRequestFailure;
this.aborted = false;
this.compress = false;
this.requestKey = requestKey;
this.requestData = requestData;
}
HttpRequest.prototype.setOrigin = function (origin) {
this.origin = origin;
return this;
};
HttpRequest.prototype.setOnError = function (errorMessage) {
if (typeof errorMessage === "string")
this.errorMessage = errorMessage;
else
this.handleRequestFailure = errorMessage;
return this;
};
HttpRequest.prototype.setOnSuccessMessage = function (successMessage) {
this.successMessage = successMessage;
return this;
};
HttpRequest.prototype.setOnResponseListener = function (listener) {
this.onResponseListener = listener;
return this;
};
HttpRequest.prototype.setLabel = function (label) {
this.label = label;
return this;
};
HttpRequest.prototype.setMethod = function (method) {
this.method = method;
return this;
};
HttpRequest.prototype.setUrlParams = function (params) {
var _this = this;
if (!params)
return this;
ts_common_1._keys(params).forEach(function (key) {
var param = params[key];
return param && typeof param === "string" && _this.setUrlParam(key, param);
});
return this;
};
HttpRequest.prototype.setUrlParam = function (key, value) {
delete this.params[key];
this.params[key] = value;
return this;
};
HttpRequest.prototype.setUrl = function (url) {
this.url = url;
return this;
};
HttpRequest.prototype.setRelativeUrl = function (relativeUrl) {
this.url = this.origin + relativeUrl;
return this;
};
HttpRequest.prototype.setTimeout = function (timeout) {
this.timeout = timeout;
return this;
};
HttpRequest.prototype.setOnProgressListener = function (onProgressListener) {
this.onProgressListener = onProgressListener;
return this;
};
HttpRequest.prototype.setHeaders = function (headers) {
var _this = this;
if (!headers)
return this;
Object.keys(headers).forEach(function (key) { return _this.setHeader(key, headers[key]); });
return this;
};
HttpRequest.prototype.addHeaders = function (headers) {
var _this = this;
if (!headers)
return this;
Object.keys(headers).forEach(function (key) { return _this.addHeader(key, headers[key]); });
return this;
};
HttpRequest.prototype.setHeader = function (_key, value) {
var key = _key.toLowerCase();
delete this.headers[key];
return this.addHeader(key, value);
};
HttpRequest.prototype.addHeader = function (_key, value) {
var key = _key.toLowerCase();
return this._addHeaderImpl(key, value);
};
HttpRequest.prototype.removeHeader = function (key) {
delete this.headers[key];
return this;
};
HttpRequest.prototype._addHeaderImpl = function (key, value) {
var _a;
var values = Array.isArray(value) ? value : [value];
if (!this.headers[key])
this.headers[key] = values;
else
(_a = this.headers[key]).push.apply(_a, values);
return this;
};
HttpRequest.prototype.setJsonBody = function (bodyObject, compress) {
if (compress === void 0) { compress = true; }
this.setHeaders({ "content-type": "application/json" });
this.setBody(JSON.stringify(bodyObject), compress);
return this;
};
HttpRequest.prototype.setBody = function (bodyAsString, compress) {
if (compress === void 0) { compress = true; }
this.body = bodyAsString;
this.compress = compress;
if (typeof bodyAsString === "string" && compress)
this.setHeader("Content-encoding", "gzip");
return this;
};
HttpRequest.prototype.asJson = function () {
if (!this.xhr)
throw new ts_common_1.BadImplementationException("No xhr object... maybe you didn't wait for the request to return??");
var response = this.xhr.response;
if (!response)
throw new ts_common_1.BadImplementationException("No xhr.response...");
return JSON.parse(response);
};
HttpRequest.prototype.asText = function () {
if (!this.xhr)
throw new ts_common_1.BadImplementationException("No xhr object... maybe you didn't wait for the request to return??");
return this.xhr.response;
};
HttpRequest.prototype.resolveResponse = function () {
var rawResponse = this.xhr && this.xhr.response;
var response = undefined;
if (rawResponse) {
try {
response = rawResponse && this.asJson();
}
catch (e) {
response = this.asText();
}
}
return response;
};
HttpRequest.prototype.execute = function (responseHandler) {
var _this = this;
// @ts-ignore
http_module_1.HttpModule.runAsync(this.label || "http request: " + this.requestKey, function () { return __awaiter(_this, void 0, void 0, function () {
var response, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.executeImpl()];
case 1:
_b.sent();
if (this.aborted)
return [2 /*return*/];
if (http_module_1.HttpModule.processDefaultResponseHandlers(this))
return [2 /*return*/];
if (this.xhr.status !== 200)
return [2 /*return*/, this.handleRequestFailure(this.getErrorResponse(), this.xhr, this.requestKey, this.errorMessage)];
response = this.resolveResponse();
this.onResponseListener && this.onResponseListener(response);
_a = responseHandler;
if (!_a) return [3 /*break*/, 3];
return [4 /*yield*/, responseHandler(response)];
case 2:
_a = (_b.sent());
_b.label = 3;
case 3:
_a;
this.handleRequestSuccess(this.requestKey, this.successMessage, this.requestData);
return [2 /*return*/];
}
});
}); });
return this;
};
HttpRequest.prototype.getErrorResponse = function () {
var rawResponse = this.xhr && this.xhr.response;
var response = undefined;
if (rawResponse) {
try {
response = rawResponse && this.asJson();
}
catch (e) {
response = { debugMessage: rawResponse };
}
}
return response;
};
HttpRequest.prototype.executeSync = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.executeImpl()];
case 1:
_a.sent();
if (this.xhr.status !== 200)
throw new HttpException(this.xhr.status, this.url);
return [2 /*return*/, this.resolveResponse()];
}
});
});
};
HttpRequest.prototype.abort = function () {
this.aborted = true;
this.xhr.abort();
};
HttpRequest.prototype.executeImpl = function () {
var _this = this;
return new Promise(function (resolve, reject) {
_this.aborted = false;
_this.xhr = new XMLHttpRequest();
_this.xhr.onreadystatechange = function () {
if (_this.xhr.readyState !== 4)
return;
resolve();
};
_this.xhr.onerror = function (err) {
if (_this.xhr.readyState === 4 && _this.xhr.status === 0) {
reject(new HttpException(404, _this.url));
return;
}
reject(err);
};
_this.xhr.ontimeout = function (err) {
reject(err);
};
var nextOperator = "?";
if (_this.url.indexOf("?") !== -1) {
nextOperator = "&";
}
var fullUrl = ts_common_1._keys(_this.params).reduce(function (url, paramKey) {
var param = _this.params[paramKey];
if (!param)
return url;
var toRet = "" + url + nextOperator + paramKey + "=" + encodeURIComponent(param);
nextOperator = "&";
return toRet;
}, _this.url);
_this.xhr.upload.onprogress = _this.onProgressListener;
_this.xhr.open(_this.method, fullUrl, true);
_this.xhr.timeout = _this.timeout;
Object.keys(_this.headers).forEach(function (key) {
_this.xhr.setRequestHeader(key, _this.headers[key].join('; '));
});
var body = _this.body;
if (typeof body === "string" && _this.compress)
return zlib_1.gzip(body, function (error, result) {
if (error)
return reject(error);
_this.xhr.send(result);
});
_this.xhr.send(body);
});
};
return HttpRequest;
}());
exports.HttpRequest = HttpRequest;
//# sourceMappingURL=http-request.js.map