@intuitionrobotics/testelot
Version:
Nu-Art Sir Testelot
197 lines • 7.82 kB
JavaScript
"use strict";
/*
* Testelot is a typescript scenario composing framework
*
* Copyright (C) 2020 Intuition Robotics
*
* 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 __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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Action_Http = exports.HttpMethod = void 0;
/**
* Created by IR on 3/18/17.
*/
const ts_common_1 = require("@intuitionrobotics/ts-common");
const Action_1 = require("./Action");
const fetch = require("node-fetch");
var HttpMethod;
(function (HttpMethod) {
HttpMethod["ALL"] = "all";
HttpMethod["POST"] = "post";
HttpMethod["GET"] = "get";
HttpMethod["PATCH"] = "patch";
HttpMethod["DELETE"] = "delete";
HttpMethod["PUT"] = "put";
HttpMethod["OPTIONS"] = "options";
HttpMethod["HEAD"] = "head";
})(HttpMethod || (exports.HttpMethod = HttpMethod = {}));
class Action_Http extends Action_1.Action {
constructor(method) {
super(Action_Http);
this.headers = {};
this.params = {};
this.responseStatus = 200;
this.method = method;
}
setUrl(url) {
this.url = url;
return this;
}
;
setBody(body) {
this.body = body;
return this;
}
;
setParams(params) {
this.params = params;
return this;
}
;
addHeader(key, value) {
this.headers[key] = value;
return this;
}
;
setResponseStatus(status) {
this.responseStatus = status;
return this;
}
setResponseProcessor(validator) {
this.responseProcessor = validator;
return this;
}
resolveBody() {
if (typeof this.body === "function")
this.body = this.body(this);
if (typeof this.body === "string")
return this.body;
this.addHeader("Accept", 'application/json');
this.addHeader("Content-Type", 'application/json');
return JSON.stringify(this.body, null, 2);
}
resolveUrl() {
if (typeof this.url === "function")
this.url = this.url(this);
return this.url + `${this.toUrlParams()}`;
}
toUrlParams() {
if (!this.params)
return "";
if (typeof this.params === "function")
this.params = this.params();
if (Object.keys(this.params).length === 0)
return "";
return `?${Object.keys(this.params).map((key) => {
return `${key}=${this.params[key]}`;
}).join("&")}`;
}
execute() {
return __awaiter(this, void 0, void 0, function* () {
const url = this.resolveUrl();
const body = this.resolveBody();
const headers = {};
for (const key of Object.keys(this.headers)) {
const value = this.headers[key];
if (typeof value !== "string") {
headers[key] = value(this);
}
else
headers[key] = value;
}
const requestBody = {
headers: JSON.parse(JSON.stringify(headers)),
body: body,
method: this.method
};
this.logInfo(`----- Method: ${requestBody.method}`);
this.logInfo(`-------- Uri: ${url}`);
if (Object.keys(headers).length > 0) {
this.logVerbose("-------- Headers --------");
for (const key of Object.keys(headers)) {
this.logVerbose(` ${key}: ${headers[key]}`);
}
this.logVerbose("-------------------------");
}
if (requestBody.body) {
this.logVerbose("--------- Request Body ----------");
this.logVerbose(body);
this.logVerbose("-------------------------");
}
return yield this.executeHttpRequest(requestBody);
});
}
;
resolveResponseBody(response) {
return __awaiter(this, void 0, void 0, function* () {
const contentType = response.headers.get("Content-Type");
if (!contentType)
return;
// @ts-ignore
let match;
switch (contentType) {
case (match = (0, ts_common_1.regexpCase)(contentType, ".*application/json.*")).input:
return yield response.json();
case (match = (0, ts_common_1.regexpCase)(contentType, ".*application/x-www-form-urlencoded.*")).input:
return decodeURI((yield response.text()));
case (match = (0, ts_common_1.regexpCase)(contentType, "^text\\/.*")).input:
return yield response.text();
default:
if (Action_Http.global_resolveResponseBody)
return Action_Http.global_resolveResponseBody(this, response);
}
throw new ts_common_1.ImplementationMissingException(`unhandled response with content-type: ${contentType}`);
});
}
executeHttpRequest(requestBody) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield fetch.default(this.resolveUrl(), requestBody);
const status = response.status;
let _responseBody = "";
const expectedStatus = this.responseStatus;
if (status !== expectedStatus || status >= 500 && status < 600) {
try {
_responseBody = yield response.text();
}
catch (ignore) {
}
this.logError(`Got Response code: ${status}`);
this.logError(`Got Response body: ${_responseBody}`);
throw new ts_common_1.Exception(`wrong status code from server. Expected: ${expectedStatus} received: ${status}`);
}
// we don't want to undefine what was already defined just because we failed...
if (status !== 200 && this.writeKey)
this.get(this.writeKey);
let responseBody = yield this.resolveResponseBody(response);
if (this.responseProcessor)
responseBody = this.responseProcessor(responseBody);
if (responseBody) {
this.logVerbose("--------- Response ----------");
this.logVerbose(typeof responseBody === "object" ? JSON.stringify(responseBody, null, 2) : responseBody);
this.logVerbose("-------------------------");
}
return responseBody;
});
}
}
exports.Action_Http = Action_Http;
//# sourceMappingURL=Action_Http.js.map