UNPKG

@calf/abra

Version:

Abra module of Calf framework.

407 lines (406 loc) 17.9 kB
"use strict"; 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 }; } }; var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ApiService = void 0; // External modules var node_fetch_1 = require("node-fetch"); var rxjs_1 = require("rxjs"); // Classes var config_class_1 = require("../classes/config.class"); /** * Function for attributes normalization, all has to start with upper case char * @param input * @returns */ var normalizeAttributes = function (input) { if (typeof input !== 'object') return input; if (Array.isArray(input)) return input.map(normalizeAttributes); return Object.keys(input).reduce(function (newObj, key) { var val = input[key]; var newVal = (typeof val === 'object') && val !== null ? normalizeAttributes(val) : val; newObj[key.toLowerCase()] = newVal; return newObj; }, {}); }; /** * Api service * @description Abra API service */ var ApiService = /** @class */ (function () { function ApiService() { // Result observable this.resultSource = new rxjs_1.Subject(); this.result$ = this.resultSource.asObservable(); // Exception observable this.exceptionSource = new rxjs_1.Subject(); this.exception$ = this.exceptionSource.asObservable(); } /** * Observe results */ ApiService.prototype.results = function () { // Return result source as observable return this.result$; }; /** * Observe exception */ ApiService.prototype.exceptions = function () { // Return exceptions source as observable return this.exception$; }; /** * Get list * @param module * @param query * @returns */ ApiService.prototype.getList = function (module, query) { return __awaiter(this, void 0, void 0, function () { var headers, target, response, result, normalized; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getRequestHeaders()]; case 1: headers = _a.sent(); return [4 /*yield*/, this.getRequestTarget()]; case 2: target = _a.sent(); return [4 /*yield*/, node_fetch_1.default([target, module, "query"].join("/"), { method: "post", body: JSON.stringify(query), headers: headers })]; case 3: response = _a.sent(); return [4 /*yield*/, this.parseResponse(response)]; case 4: result = _a.sent(); normalized = !(result instanceof Array) ? [result] : result; // Emit result this.resultSource.next(normalized); // Return normalized result return [2 /*return*/, normalizeAttributes(normalized)]; } }); }); }; /** * Get * @description Get object detail * @param module * @param id * @returns */ ApiService.prototype.get = function (module, id) { return __awaiter(this, void 0, void 0, function () { var headers, target, response, result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getRequestHeaders()]; case 1: headers = _a.sent(); return [4 /*yield*/, this.getRequestTarget()]; case 2: target = _a.sent(); return [4 /*yield*/, node_fetch_1.default([target, module, id].join("/"), { method: "get", headers: headers })]; case 3: response = _a.sent(); return [4 /*yield*/, this.parseResponse(response)]; case 4: result = _a.sent(); // Emit result this.resultSource.next(result); // Return result return [2 /*return*/, normalizeAttributes(result)]; } }); }); }; /** * Request * @description Make request to given endpoint without processing * the result * @param method * @param module * @param segments * @param payload * @param fields */ ApiService.prototype.execute = function (method, module, rawResponse, segments, fields, queryParams, payload) { if (rawResponse === void 0) { rawResponse = true; } if (fields === void 0) { fields = []; } if (queryParams === void 0) { queryParams = []; } return __awaiter(this, void 0, void 0, function () { var headers, target, url, index, param, options, response, result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getRequestHeaders()]; case 1: headers = _a.sent(); return [4 /*yield*/, this.getRequestTarget()]; case 2: target = _a.sent(); url = __spreadArrays([target, module], (segments || [])).join("/"); // Check for fields if ((fields || []).length) { // Add fields as select query url = url + "?select=" + fields.join(","); } // Check for query params if (queryParams && queryParams.length) { // Iterate params for (index = 0; index < queryParams.length; index++) { param = queryParams[index]; // First element and fields are also set if (!index && (!fields || !fields.length)) { url = url + "?" + param.name + "=" + param.value; } else { url = url + "&" + param.name + "=" + param.value; } } } options = { method: method, headers: headers }; // Check for payload if (typeof payload !== "undefined") { // Set options body options.body = JSON.stringify(payload); } if (!rawResponse) return [3 /*break*/, 3]; return [2 /*return*/, node_fetch_1.default(url, options)]; case 3: return [4 /*yield*/, node_fetch_1.default(url, options)]; case 4: response = _a.sent(); return [4 /*yield*/, this.parseResponse(response)]; case 5: result = _a.sent(); // Emit result this.resultSource.next(result); // Return result return [2 /*return*/, normalizeAttributes(result)]; } }); }); }; /** * Update * @description Update existing object * @param module * @param id * @param payload * @param fields * @returns */ ApiService.prototype.update = function (module, id, payload, fields) { if (fields === void 0) { fields = ["id"]; } return __awaiter(this, void 0, void 0, function () { var headers, target, url, response, result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getRequestHeaders()]; case 1: headers = _a.sent(); return [4 /*yield*/, this.getRequestTarget()]; case 2: target = _a.sent(); url = [target, module, id].join("/"); // Check for fields if ((fields || []).length) { // Add fields as select query url = url + "?select=" + fields.join(","); } return [4 /*yield*/, node_fetch_1.default(url, { method: "put", body: JSON.stringify(payload), headers: headers })]; case 3: response = _a.sent(); return [4 /*yield*/, this.parseResponse(response)]; case 4: result = _a.sent(); // Emit result this.resultSource.next(result); // Return result return [2 /*return*/, normalizeAttributes(result)]; } }); }); }; /** * Create * @description Create new object * @param module * @param payload * @param fields */ ApiService.prototype.create = function (module, payload, fields) { if (fields === void 0) { fields = ["id"]; } return __awaiter(this, void 0, void 0, function () { var headers, target, url, response, result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getRequestHeaders()]; case 1: headers = _a.sent(); return [4 /*yield*/, this.getRequestTarget()]; case 2: target = _a.sent(); url = [target, module].join("/"); // Check for fields if ((fields || []).length) { // Add fields as select query url = url + "?select=" + fields.join(","); } return [4 /*yield*/, node_fetch_1.default(url, { method: "post", body: JSON.stringify(payload), headers: headers })]; case 3: response = _a.sent(); return [4 /*yield*/, this.parseResponse(response)]; case 4: result = _a.sent(); // Emit result this.resultSource.next(result); // Return result return [2 /*return*/, normalizeAttributes(result)]; } }); }); }; /** * Delete * @description Delete object * @param module * @param id */ ApiService.prototype.delete = function (module, id) { return __awaiter(this, void 0, void 0, function () { var headers, target; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getRequestHeaders()]; case 1: headers = _a.sent(); return [4 /*yield*/, this.getRequestTarget()]; case 2: target = _a.sent(); // Delete data return [4 /*yield*/, node_fetch_1.default([target, module, id].join("/"), { method: "delete", headers: headers })]; case 3: // Delete data _a.sent(); return [2 /*return*/]; } }); }); }; /** * Parse response * @param response * @returns */ ApiService.prototype.parseResponse = function (response) { return __awaiter(this, void 0, void 0, function () { var contentEncoding; return __generator(this, function (_a) { try { contentEncoding = response.headers.get("content-encoding"); // No Content success status response code if (response.status === 204) { // Empty object return [2 /*return*/, {}]; } // Get json return [2 /*return*/, response.json()]; } catch (e) { // Rethrow error throw e; } return [2 /*return*/]; }); }); }; /** * Get request target * @description Get target for request */ ApiService.prototype.getRequestTarget = function () { return __awaiter(this, void 0, void 0, function () { var parts, host; return __generator(this, function (_a) { parts = []; host = config_class_1.AbraConfig.host; // Add port to host if needed config_class_1.AbraConfig.port && (host = host + ":" + config_class_1.AbraConfig.port); // Check for ssl if (config_class_1.AbraConfig.ssl) { // Add SSL version parts.push("https://" + host); } else { // Add non-SSL version parts.push("http://" + host); } // Add instance to parts config_class_1.AbraConfig.instance && parts.push(config_class_1.AbraConfig.instance); // Return target return [2 /*return*/, parts.join("/")]; }); }); }; /** * Get request headers * @description Get headers for request */ ApiService.prototype.getRequestHeaders = function () { return __awaiter(this, void 0, void 0, function () { var headers; return __generator(this, function (_a) { headers = { "Content-type": "application/json" }; // Add authorization headers["Authorization"] = "Basic " + Buffer.from(config_class_1.AbraConfig.auth.username + ":" + config_class_1.AbraConfig.auth.password).toString("base64"); // Return headers return [2 /*return*/, headers]; }); }); }; return ApiService; }()); exports.ApiService = ApiService;