@seancrowe/chiliconnector-base
Version:
Wrapper around Fetch for working with CHILI publish web services
279 lines (266 loc) • 10.5 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var crossFetch = require('cross-fetch');
var fastXmlParser = require('fast-xml-parser');
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(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());
});
}
class ChiliResponse {
constructor(response) {
this._response = response;
this._isNode =
typeof process !== "undefined" &&
process.versions != null &&
process.versions.node != null;
}
get ok() {
return this._response.ok;
}
get headers() {
return this._response.headers;
}
get redirected() {
return this._response.redirected;
}
get status() {
return this._response.status;
}
get statusText() {
return this._response.statusText;
}
get type() {
return this._response.type;
}
get url() {
return this._response.url;
}
clone() {
return new ChiliResponse(this._response.clone());
}
get streamUsed() {
return this._response.bodyUsed;
}
readAsNodeStream() {
if (!this._isNode) {
return null;
}
else {
return this._response.body;
}
}
readAsBrowserStream() {
if (this._isNode) {
return null;
}
return this._response.body;
}
readAsStream() {
if (!this._isNode) {
return this._response.body;
}
else {
return this._response.body;
}
}
get body() {
return this.readAsStream();
}
readAsArrayBuffer() {
return __awaiter(this, void 0, void 0, function* () {
return this._response.arrayBuffer();
});
}
arrayBuffer() {
return __awaiter(this, void 0, void 0, function* () {
return this.readAsArrayBuffer();
});
}
readAsBlob() {
return __awaiter(this, void 0, void 0, function* () {
return this._response.blob();
});
}
blob() {
return __awaiter(this, void 0, void 0, function* () {
return this.readAsBlob();
});
}
readAsString() {
return __awaiter(this, void 0, void 0, function* () {
return this._response.text();
});
}
text() {
return __awaiter(this, void 0, void 0, function* () {
return this.readAsString();
});
}
readAsJson() {
return __awaiter(this, void 0, void 0, function* () {
return ChiliResponse._jsonifyResponse(yield this._response.text());
});
}
json() {
return __awaiter(this, void 0, void 0, function* () {
return this.readAsJson();
});
}
static _jsonifyResponse(response) {
let data = fastXmlParser.parse(response, {
ignoreAttributes: false,
attrNodeName: false,
attributeNamePrefix: "",
});
const firstKeys = Object.keys(data);
if (firstKeys.length == 1) {
if (typeof data[firstKeys[0]] == "object") {
data = data[firstKeys[0]];
}
}
return data;
}
}
class ChiliFetch {
constructor(basePath, baseRequestSettings) {
var _a, _b, _c;
this._basePath = basePath;
this._defaultHeaders = (_a = baseRequestSettings === null || baseRequestSettings === void 0 ? void 0 : baseRequestSettings.headers) !== null && _a !== void 0 ? _a : new crossFetch.Headers();
this._defaultTimeout = (_b = baseRequestSettings === null || baseRequestSettings === void 0 ? void 0 : baseRequestSettings.timeout) !== null && _b !== void 0 ? _b : 0;
this._defaultMode = (_c = baseRequestSettings === null || baseRequestSettings === void 0 ? void 0 : baseRequestSettings.mode) !== null && _c !== void 0 ? _c : "cors";
let foundContentType = false;
for (const [key] of this._defaultHeaders.entries()) {
if (key.toLowerCase() === "content-type") {
foundContentType = true;
}
}
if (!foundContentType) {
this._defaultHeaders.set("Content-Type", "application/json");
}
}
set apiKey(apikey) {
for (const [key] of this._defaultHeaders.entries()) {
if (key.toLowerCase() == "api-key") {
this._defaultHeaders.delete(key);
}
}
if (apikey != null) {
this._defaultHeaders.set("api-key", apikey);
}
}
get apiKey() {
return this._defaultHeaders.get("api-key");
}
static _encode(val) {
return encodeURIComponent(val)
.replace(/%3A/gi, ":")
.replace(/%24/g, "$")
.replace(/%2C/gi, ",")
.replace(/%20/g, "+")
.replace(/%5B/gi, "[")
.replace(/%5D/gi, "]");
}
fetch(path, chiliRequestConfig) {
var _a, _b, _c, _d, _e, _f;
return __awaiter(this, void 0, void 0, function* () {
let timeoutHandler = null;
const timeoutTime = (_b = (_a = chiliRequestConfig === null || chiliRequestConfig === void 0 ? void 0 : chiliRequestConfig.timeout) !== null && _a !== void 0 ? _a : this._defaultTimeout) !== null && _b !== void 0 ? _b : 0;
if (timeoutTime != null && timeoutTime > 1) {
timeoutHandler = setTimeout(() => {
throw new Error("Request timeout - request took longer than " +
timeoutTime +
"ms to respond");
}, timeoutTime);
}
const method = (_c = chiliRequestConfig === null || chiliRequestConfig === void 0 ? void 0 : chiliRequestConfig.method) !== null && _c !== void 0 ? _c : "GET";
const mode = (_e = (_d = chiliRequestConfig === null || chiliRequestConfig === void 0 ? void 0 : chiliRequestConfig.mode) !== null && _d !== void 0 ? _d : this._defaultMode) !== null && _e !== void 0 ? _e : "cors";
const parameters = [];
if ((chiliRequestConfig === null || chiliRequestConfig === void 0 ? void 0 : chiliRequestConfig.parameters) != null) {
for (const [key, value] of Object.entries(chiliRequestConfig.parameters)) {
if (value == null) {
continue;
}
parameters.push(ChiliFetch._encode(key) + "=" + ChiliFetch._encode(value));
}
}
const fullPath = this._basePath +
path +
(path.indexOf("?") === -1 ? "?" : "&") +
parameters.join("&");
let body = method != "GET" && method != "HEAD"
? (_f = chiliRequestConfig === null || chiliRequestConfig === void 0 ? void 0 : chiliRequestConfig.body) !== null && _f !== void 0 ? _f : undefined
: undefined;
if (body != null) {
if (typeof body == "object") {
body = JSON.stringify(body);
}
}
const response = yield crossFetch.fetch(fullPath, {
method: method,
mode: mode,
headers: this._defaultHeaders,
body: body,
});
if (timeoutHandler != null) {
clearTimeout(timeoutHandler);
}
return new ChiliResponse(response);
});
}
}
class ChiliConnector {
constructor(basePath, baseRequestSettings) {
this._basePath = basePath;
this._chiliFetch = new ChiliFetch(basePath, baseRequestSettings);
}
set apiKey(apiKey) {
this._chiliFetch.apiKey = apiKey;
}
get apiKey() {
return this._chiliFetch.apiKey;
}
}
function isConnectionGoodV1(basePath, throwError) {
return __awaiter(this, void 0, void 0, function* () {
const chiliFetch = new ChiliFetch(basePath);
try {
const responseDate = yield chiliFetch.fetch(`/rest-api/v1/system/server/date`, { method: "GET" });
if (responseDate.ok &&
(yield responseDate.readAsString()).includes("date")) {
const responseKey = yield chiliFetch.fetch(`/rest-api/v1/system/apikey?environmentNameOrURL=testConnector_${Date.now()}`, { method: "GET" });
return (yield responseKey.readAsString()).includes("Invalid Environment");
}
}
catch (e) {
if (throwError) {
throw e;
}
}
return false;
});
}
var types = /*#__PURE__*/Object.freeze({
__proto__: null
});
exports.ChiliConnector = ChiliConnector;
exports.ChiliFetch = ChiliFetch;
exports.ChiliResponse = ChiliResponse;
exports.ChiliTypes = types;
exports.isConnectionGoodV1 = isConnectionGoodV1;