UNPKG

jade-integration-utils

Version:

A tool made for any type of http requisitions and to manage localstorage. This package works into Angular and Ionic projects (maybe you can run this in ReactNative, MAYBE!).

1,104 lines (1,061 loc) 49.5 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common/http'), require('@angular/router'), require('@angular/common'), require('@angular/platform-browser')) : typeof define === 'function' && define.amd ? define('jade-integration-utils', ['exports', '@angular/core', '@angular/common/http', '@angular/router', '@angular/common', '@angular/platform-browser'], factory) : (global = global || self, factory(global['jade-integration-utils'] = {}, global.ng.core, global.ng.common.http, global.ng.router, global.ng.common, global.ng.platformBrowser)); }(this, (function (exports, core, http, router, common, platformBrowser) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ 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); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } 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()); }); } function __generator(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 }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { 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; }; function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } var EventEmitterService = /** @class */ (function () { function EventEmitterService() { } EventEmitterService.get = function (nomeEvento) { if (!this.emitters[nomeEvento]) this.emitters[nomeEvento] = new core.EventEmitter(); return this.emitters[nomeEvento]; }; EventEmitterService.emitters = {}; EventEmitterService.ɵprov = core["ɵɵdefineInjectable"]({ factory: function EventEmitterService_Factory() { return new EventEmitterService(); }, token: EventEmitterService, providedIn: "root" }); EventEmitterService = __decorate([ core.Injectable({ providedIn: 'root' }) ], EventEmitterService); return EventEmitterService; }()); var StorageService = /** @class */ (function () { function StorageService() { } StorageService.get = function (index) { var obj = localStorage.getItem(index); return obj ? JSON.parse(obj) : null; }; StorageService.set = function (index, object) { localStorage.setItem(index, JSON.stringify(object)); }; StorageService.getSession = function (index) { var obj = sessionStorage.getItem(index); return obj ? JSON.parse(obj) : null; }; StorageService.setSession = function (index, object) { sessionStorage.setItem(index, JSON.stringify(object)); }; StorageService.getTemp = function () { var obj = sessionStorage.getItem('temp'); return obj ? JSON.parse(obj) : null; }; StorageService.setTemp = function (object) { sessionStorage.setItem('temp', JSON.stringify(object)); }; StorageService.clearTemp = function () { sessionStorage.removeItem('temp'); }; StorageService.clear = function () { localStorage.clear(); sessionStorage.clear(); }; StorageService.APIMaps = function () { return "AIzaSyBiQp1xNr0h8WLV_6OlbMu2E83ezjShoAk"; }; StorageService.ɵprov = core["ɵɵdefineInjectable"]({ factory: function StorageService_Factory() { return new StorageService(); }, token: StorageService, providedIn: "root" }); StorageService = __decorate([ core.Injectable({ providedIn: 'root' }) ], StorageService); return StorageService; }()); var HttpStatusService = /** @class */ (function () { function HttpStatusService(http) { this.http = http; this._url = ''; this._AUTH = "auth"; this._options = { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, responseType: "json" }; } HttpStatusService.prototype.configure = function (url) { this._url = url; }; HttpStatusService.prototype.set_token = function (auth) { StorageService.set(this._AUTH, "Bearer " + auth); this._options.headers.Authorization = (this.get_token()) ? StorageService.get(this._AUTH) : null; }; HttpStatusService.prototype.get_token = function () { return StorageService.get(this._AUTH); }; HttpStatusService.prototype.get = function (endpoint) { return this.http.get(this._url + endpoint, this._options).toPromise(); }; HttpStatusService.prototype.get_file = function (endpoint) { this.options.responseType = "blob"; return this.http.get(this._url + endpoint, this._options).toPromise(); }; HttpStatusService.prototype.post = function (endpoint, body) { return this.http.post(this._url + endpoint, body, this._options).toPromise(); }; HttpStatusService.prototype.formData = function (endpoint, body) { delete this._options.headers["Content-Type"]; return this.http.post(this._url + endpoint, body, this._options).toPromise(); }; HttpStatusService.prototype.put = function (endpoint, body) { return this.http.put(this._url + endpoint, body, this._options).toPromise(); }; HttpStatusService.prototype.delete = function (endpoint) { return this.http.delete(this._url + endpoint, this._options).toPromise(); }; Object.defineProperty(HttpStatusService.prototype, "options", { get: function () { return this._options; }, set: function (option) { this._options = option; }, enumerable: true, configurable: true }); HttpStatusService.prototype.default_options = function () { this._options = { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, responseType: "json" }; }; HttpStatusService.ctorParameters = function () { return [ { type: http.HttpClient } ]; }; HttpStatusService.ɵprov = core["ɵɵdefineInjectable"]({ factory: function HttpStatusService_Factory() { return new HttpStatusService(core["ɵɵinject"](http.HttpClient)); }, token: HttpStatusService, providedIn: "root" }); HttpStatusService = __decorate([ core.Injectable({ providedIn: 'root' }) ], HttpStatusService); return HttpStatusService; }()); var GenericService = /** @class */ (function () { function GenericService(http, router) { this.http = http; this.router = router; this._auth = "Authentication"; } /** * configureHttp */ GenericService.prototype.configureHttp = function (url) { this.http.configure(url); }; /** * * @param endpoint end point to access * @param queryParams = null; a string for example: name=Ronaldo&type=2 doesn't write ? \n(In case send GET without queryParams, just pass null end use endpoint to do it. Ex: cars/example) */ GenericService.prototype.get = function (endpoint, queryParams) { var new_endpoint = ''; if (queryParams) { console.log(queryParams); new_endpoint = '/' + endpoint + '?' + queryParams; } else { new_endpoint = '/' + endpoint; } this.default_options(); this.auth = this.auth; return this.http.get(new_endpoint); }; /** * * @param endpoint end point to access * @param queryParams = null; a string for example: name=Ronaldo&type=2 doesn't write ? \n(In case send GET without queryParams, just pass null end use endpoint to do it. Ex: cars/example) */ GenericService.prototype.get_file = function (endpoint, queryParams) { var new_endpoint = ''; if (queryParams) { console.log(queryParams); new_endpoint = '/' + endpoint + '?' + queryParams; } else { new_endpoint = '/' + endpoint; } return this.http.get_file(new_endpoint); }; /** * * @param endpoint end point to access * @param queryParams = null; a string for example: name=Ronaldo&type=2 doesn't write ? \n(In case send GET without queryParams, just pass null end use endpoint to do it. Ex: cars/example) */ GenericService.prototype.get_any = function (endpoint, queryParams) { var new_endpoint = ''; if (queryParams) { console.log(queryParams); new_endpoint = '/' + endpoint + '?' + queryParams; } else { new_endpoint = '/' + endpoint; } this.default_options(); this.auth = this.auth; return this.http.get(new_endpoint); }; GenericService.prototype.getById = function (id, endpoint) { this.default_options(); this.auth = this.auth; return this.http.get('/' + endpoint + '/' + id); }; /** * Use to request POST. * @param body K -> K is the model dto to pass with body * @param endpoint String -> string to be pass with endpoint access */ GenericService.prototype.post = function (body, endpoint) { this.default_options(); this.auth = this.auth; return this.http.post('/' + endpoint, body); }; /** * Use to request formData with files * Don't forget.to call default_options * @param body K -> K is the model dto to pass with body * @param endpoint String -> string to be pass with endpoint access */ GenericService.prototype.formData = function (body, endpoint) { return this.http.formData('/' + endpoint, body); }; /** * Use to request POST. * @param body K -> K is the model dto to pass with body * @param endpoint String -> string to be pass with endpoint access */ GenericService.prototype.put = function (body, endpoint) { return this.http.put('/' + endpoint, body); }; GenericService.prototype.delete = function (id, endpoint) { return this.http.delete('/' + endpoint + '/' + id); }; GenericService.prototype.set_token = function (auth) { this.http.set_token(auth); }; GenericService.prototype.get_token = function () { return this.http.get_token(); }; Object.defineProperty(GenericService.prototype, "options", { get: function () { return this.http.options; }, set: function (options) { this.http.options = options; }, enumerable: true, configurable: true }); GenericService.prototype.default_options = function () { this.http.default_options(); }; Object.defineProperty(GenericService.prototype, "auth", { get: function () { return StorageService.get(this._auth); }, set: function (auth) { StorageService.set(this._auth, auth); this.set_token(auth); }, enumerable: true, configurable: true }); GenericService.prototype.downloadFile = function (data) { var blob = new Blob([data]); var url = window.URL.createObjectURL(blob); window.open(url); }; GenericService.ctorParameters = function () { return [ { type: HttpStatusService }, { type: router.Router } ]; }; GenericService.ɵprov = core["ɵɵdefineInjectable"]({ factory: function GenericService_Factory() { return new GenericService(core["ɵɵinject"](HttpStatusService), core["ɵɵinject"](router.Router)); }, token: GenericService, providedIn: "root" }); GenericService = __decorate([ core.Injectable({ providedIn: 'root' }) ], GenericService); return GenericService; }()); var HttpMethod = /** @class */ (function () { function HttpMethod() { } HttpMethod.GET = "get"; HttpMethod.POST = "post"; HttpMethod.PUT = "put"; HttpMethod.DELETE = "delete"; HttpMethod.OPTIONS = "options"; HttpMethod.PATCH = "patch"; return HttpMethod; }()); var HttpXHRService = /** @class */ (function () { function HttpXHRService(standard_api_url, headers) { this._AUTH = 'auth'; this._standard_url = standard_api_url; this._xhttp = new XMLHttpRequest(); if (!headers) { this._headers = new Array(); this._headers.push({ header: 'Content-Type', value: 'application/json' }); this._headers.push({ header: 'Authorization', value: StorageService.get(this._AUTH), }); this._headers.push({ header: 'Accept', value: '*/*' }); this._headers.push({ header: 'Access-Control-Allow-Credentials', value: 'true', }); this._headers.push({ header: 'Access-Control-Allow-Origin', value: 'http://localhost:4200', }); this._headers.push({ header: 'Access-Control-Allow-Methods', value: 'GET, POST, PATCH, DELETE, PUT, OPTIONS', }); this._headers.push({ header: 'Access-Control-Allow-Headers', value: 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With', }); } else { this._headers = headers; } } HttpXHRService.prototype.set_token = function (auth) { StorageService.set(this._AUTH, 'Bearer ' + auth); }; HttpXHRService.prototype.get_token = function () { return StorageService.get(this._AUTH); }; HttpXHRService.prototype.get = function (endpoint) { this._xhttp.open(HttpMethod.GET, this._standard_url + endpoint); return this._send_request(); }; HttpXHRService.prototype.get_file = function (endpoint) { this._xhttp.open(HttpMethod.GET, this._standard_url + endpoint); return this._send_request(); }; HttpXHRService.prototype.post = function (endpoint, body) { this._xhttp.open(HttpMethod.POST, this._standard_url + endpoint); return this._send_request(body); }; HttpXHRService.prototype.formData = function (endpoint, body) { this._xhttp.open(HttpMethod.POST, this._standard_url + endpoint); return this._send_request(body); }; HttpXHRService.prototype.put = function (endpoint, body) { this._xhttp.open(HttpMethod.PUT, this._standard_url + endpoint); return this._send_request(body); }; HttpXHRService.prototype.delete = function (endpoint) { this._xhttp.open(HttpMethod.DELETE, this._standard_url + endpoint); return this._send_request(); }; HttpXHRService.prototype._send_request = function (data, timeout) { var _this = this; if (data === void 0) { data = null; } if (timeout === void 0) { timeout = 60000; } var token = this.get_token(); this._xhttp.setRequestHeader('Content-Type', 'application/json'); for (var index = 0; index < this._headers.length; index++) { var header = this._headers[index]; if (header.header != 'Authorization') { this._xhttp.setRequestHeader(header.header, header.value); } if (header.header == "Authorization" && token != null) { this._xhttp.setRequestHeader(header.header, token); } } this._xhttp.withCredentials = token ? true : false; this._xhttp.responseType = 'json'; return new Promise(function (resolve, reject) { _this._xhttp.onreadystatechange = function () { if (this.readyState == 4) { resolve(this.response); } }; _this._xhttp.send(JSON.stringify(data)); if (timeout) { setTimeout(function () { reject('timeout'); if (this._xhttp) this._xhttp.abort(); else this._xhttp = new XMLHttpRequest(); }, timeout); } }); }; return HttpXHRService; }()); var XHRManager = /** @class */ (function () { function XHRManager(api_url, endpoint) { this._auth = "Authentication"; this.http_xhr = new HttpXHRService(api_url); this._endpoint = endpoint; } /** * * @param endpoint end point to access * @param queryParams = null; a string for example: name=Ronaldo&type=2 doesn't write ? \n(In case send GET without queryParams, just pass null end use endpoint to do it. Ex: cars/example) */ XHRManager.prototype.get = function (endpoint, queryParams) { var new_endpoint = ''; if (queryParams) { new_endpoint = '/' + endpoint + '?' + queryParams; } else { new_endpoint = '/' + endpoint; } return this.http_xhr.get(new_endpoint); }; /** * * @param endpoint end point to access * @param queryParams = null; a string for example: name=Ronaldo&type=2 doesn't write ? \n(In case send GET without queryParams, just pass null end use endpoint to do it. Ex: cars/example) */ XHRManager.prototype.get_file = function (endpoint, queryParams) { var new_endpoint = ''; if (queryParams) { new_endpoint = '/' + endpoint + '?' + queryParams; } else { new_endpoint = '/' + endpoint; } return this.http_xhr.get_file(new_endpoint); }; /** * * @param endpoint end point to access * @param queryParams = null; a string for example: name=Ronaldo&type=2 doesn't write ? \n(In case send GET without queryParams, just pass null end use endpoint to do it. Ex: cars/example) */ XHRManager.prototype.get_any = function (endpoint, queryParams) { var new_endpoint = ''; if (queryParams) { new_endpoint = '/' + endpoint + '?' + queryParams; } else { new_endpoint = '/' + endpoint; } return this.http_xhr.get(new_endpoint); }; XHRManager.prototype.getById = function (id, endpoint) { return this.http_xhr.get('/' + endpoint + '/' + id); }; /** * Use to request POST. * @param body K -> K is the model dto to pass with body * @param endpoint String -> string to be pass with endpoint access */ XHRManager.prototype.post = function (body, endpoint) { return this.http_xhr.post('/' + endpoint, body); }; /** * Use to request formData with files * Don't forget.to call default_options * @param body K -> K is the model dto to pass with body * @param endpoint String -> string to be pass with endpoint access */ XHRManager.prototype.formData = function (body, endpoint) { return this.http_xhr.formData('/' + endpoint, body); }; /** * Use to request POST. * @param body K -> K is the model dto to pass with body * @param endpoint String -> string to be pass with endpoint access */ XHRManager.prototype.put = function (body, endpoint) { return this.http_xhr.put('/' + endpoint, body); }; XHRManager.prototype.delete = function (id, endpoint) { return this.http_xhr.delete('/' + endpoint + '/' + id); }; XHRManager.prototype.set_token = function (auth) { this.http_xhr.set_token(auth); }; XHRManager.prototype.get_token = function () { return this.http_xhr.get_token(); }; Object.defineProperty(XHRManager.prototype, "auth", { get: function () { return StorageService.get(this._auth); }, set: function (auth) { StorageService.set(this._auth, auth); this.set_token(auth); }, enumerable: true, configurable: true }); XHRManager.prototype.downloadFile = function (data) { var blob = new Blob([data]); var url = window.URL.createObjectURL(blob); window.open(url); }; return XHRManager; }()); var CheckRoleDirective = /** @class */ (function () { function CheckRoleDirective(el, renderer) { var _this = this; var user = StorageService.getSession('user'); setTimeout(function () { if (user !== null && _this.roles.indexOf(user.role.sigla) == -1) { renderer.setStyle(el.nativeElement, 'display', 'none'); } }, 100); } CheckRoleDirective.ctorParameters = function () { return [ { type: core.ElementRef }, { type: core.Renderer2 } ]; }; __decorate([ core.Input('checkRole') ], CheckRoleDirective.prototype, "roles", void 0); CheckRoleDirective = __decorate([ core.Directive({ selector: '[jiuCheckRole]' }) ], CheckRoleDirective); return CheckRoleDirective; }()); function loading(flag) { return function (target, key, descriptor) { var originalMethod = descriptor.value; descriptor.value = function () { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this[flag] = true; var result = originalMethod.apply(this, args); if (result) { result.next = function (val) { _this[flag] = false; return result._next(val); }; result.error = function (err) { //console.log(err); _this[flag] = false; return result._error(err); }; } else { this[flag] = false; } return result; }; return descriptor; }; } var DataService = /** @class */ (function () { function DataService(api_url, endpoint) { this._endpoint = ""; this.xMan = new XHRManager(api_url, endpoint); this.element_list = new Array(); this.loading = false; this._endpoint = endpoint; } DataService.prototype.remove_e_query = function (query) { query = query.startsWith("&") ? query.replace(query.charAt(0), "") : query; return query; }; DataService.prototype.getById = function (id, callbackHandler) { var _this = this; this.loading = true; this.xMan.getById(id, this._endpoint) .then(function (result) { _this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; DataService.prototype.bind_results = function (result) { var _a, _b, _c; this.page = (_a = result === null || result === void 0 ? void 0 : result.page) !== null && _a !== void 0 ? _a : this.page; this.fetch = (_b = result === null || result === void 0 ? void 0 : result.fetch) !== null && _b !== void 0 ? _b : this.fetch; this.itemsCount = (_c = result === null || result === void 0 ? void 0 : result.itemsCount) !== null && _c !== void 0 ? _c : this.itemsCount; if (result.objects != null) this.element_list = result.objects; this.results = result; this.get_pages_array(); }; DataService.prototype.get = function (filter, callbackHandler, pagination) { var _this = this; if (pagination === void 0) { pagination = false; } this.loading = true; var query = this.serialize_query(filter) + (pagination ? '&' + this.get_pagination_query() : ''); console.log(query); this.xMan.get(this._endpoint, query) .then(function (result) { _this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; DataService.prototype.getAll = function (callbackHandler, pagination) { var _this = this; if (pagination === void 0) { pagination = false; } this.loading = true; var pagination_query = (pagination ? this.get_pagination_query() : ''); console.log(pagination); this.xMan.get(this._endpoint, pagination_query) .then(function (result) { _this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; DataService.prototype.next = function (filter) { this.page += 1; this.get(filter, true); }; DataService.prototype.previous = function (filter) { if (this.page > 1) this.page -= 1; this.get(filter, true); }; /** * calls a http get to not configured endpoint * * @param endpoint another endpoint */ DataService.prototype.get_by_endpoint = function (endpoint, callbackHandler, query_params, pagination) { var _this = this; if (pagination === void 0) { pagination = false; } this.loading = true; console.log(pagination); this.xMan.get(endpoint + (pagination ? this.get_pagination_query() : '')) .then(function (result) { _this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; /** * this function calls a http post from before configured api * * @param body parameter that send's a different custom body * @param callbackHandler @optional function to call when requests finish * @param message @optional string to show after requests finish */ DataService.prototype.post = function (body, callbackHandler) { var _this = this; this.loading = true; this.xMan.post(this.remove_resource(body), this._endpoint) .then(function (result) { _this.results = result; if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; /** * this function calls a http post from before configured api * * @param body parameter that send's a custom body * @param callbackHandler @optional function to call when requests finish * @param message @optional string to show after requests finish */ DataService.prototype.create = function (body, callbackHandler) { var _this = this; this.loading = true; this.xMan.post(this.remove_resource(body), this._endpoint) .then(function (result) { _this.results = result; if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; /** * call's a Put method to the url before configured * @param body of requisition of request * @param callbackHandler function that call's on request's finished * @param message @optional string to show after requests finish */ DataService.prototype.update = function (body, callbackHandler) { var _this = this; this.loading = true; this.xMan.put(this.remove_resource(body), this._endpoint) .then(function (result) { _this.results = result; if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; /** * call's a Put method to the url before configured * @param body of requisition of request * @param callbackHandler function that call's on request's finished * @param message @optional string to show after requests finish */ DataService.prototype.put = function (body, callbackHandler) { var _this = this; this.loading = true; this.xMan.put(body, this._endpoint) .then(function (result) { _this.results = result; if (callbackHandler) callbackHandler(result); }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; /** * calls http DELETE to configured endpoint * * @param id Id to delete * @param callbackHandler a function to run after delete function as done */ DataService.prototype.delete = function (id, callbackHandler) { var _this = this; this.loading = true; this.xMan.delete(id, this._endpoint) .then(function (results) { if (results.target) { if (callbackHandler) callbackHandler(results); } else { alert("Ocorreu um erro!"); } }) .catch(function (error) { return _this.showError(error); }) .finally(function () { return _this.loading = false; }); }; /** * Set's Authentication bearer * @param auth strings containing authentication bearer */ DataService.prototype.set_auth = function (auth) { this.xMan.set_token(auth); }; DataService.prototype.get_auth = function () { return this.xMan.get_token(); }; DataService.prototype.get_pages_array = function () { this.page_array = new Array(); var pagesCount = this.itemsCount / this.fetch; for (var index = 1; index <= pagesCount; index++) { this.page_array.push(index); } }; DataService.prototype.get_pagination_query = function () { return "fetch=" + this.fetch + "&page=" + this.page; }; DataService.prototype.show_success = function (msg) { alert(msg || 'Saved with success'); }; DataService.prototype.showError = function (error) { console.log("***API ERROR REPORT***"); console.log(error); console.log("--------------------"); }; DataService.prototype.logout = function () { StorageService.clear(); this.xMan.auth = ''; window.location.reload(); }; DataService.prototype.serialize_query = function (obj) { var str = []; for (var p in obj) { if (typeof obj[p] === 'object') { for (var key in obj[p]) { if (p == 'resource') continue; if (Object.prototype.hasOwnProperty.call(obj[p], key)) { var element = obj[p][key]; if (this.serialize_query(obj[p])) str.push(encodeURIComponent(p) + "." + this.serialize_query(obj[p])); } } } else if (obj.hasOwnProperty(p)) { if (encodeURIComponent(obj[p])) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } } var results = str.join("&"); return results; }; DataService.prototype.auto_bind = function (result, target) { for (var p in result) { if (target.hasOwnProperty(p) && result.hasOwnProperty(p)) { target[p] = result[p]; } } }; DataService.prototype.remove_resource = function (target) { this.target = JSON.parse(JSON.stringify(target)); for (var p in this.target) { if (this.target.hasOwnProperty(p)) { if (p == 'resource' || p == 'endpoint') { delete this.target[p]; } ; } } return this.target; }; DataService.normalizeString = function (text) { text = text.toLowerCase(); text = text.replace(new RegExp('[ÁÀÂÃ]', 'gi'), 'a'); text = text.replace(new RegExp('[ÉÈÊ]', 'gi'), 'e'); text = text.replace(new RegExp('[ÍÌÎ]', 'gi'), 'i'); text = text.replace(new RegExp('[ÓÒÔÕ]', 'gi'), 'o'); text = text.replace(new RegExp('[ÚÙÛ]', 'gi'), 'u'); text = text.replace(new RegExp('[Ç]', 'gi'), 'c'); text = text.replace(/[^a-z0-9 -]/g, ''); return text; }; DataService.user_session = "session-user"; return DataService; }()); var JadeIntegrationUtilsComponent = /** @class */ (function () { function JadeIntegrationUtilsComponent() { } JadeIntegrationUtilsComponent.prototype.ngOnInit = function () { }; JadeIntegrationUtilsComponent = __decorate([ core.Component({ selector: 'JadeIntegrationUtilsComponent', template: "" }) ], JadeIntegrationUtilsComponent); return JadeIntegrationUtilsComponent; }()); var JadeIntegrationUtilsModule = /** @class */ (function () { function JadeIntegrationUtilsModule(_injector) { this._injector = _injector; exports.InjectorInstance = this._injector; } JadeIntegrationUtilsModule.ctorParameters = function () { return [ { type: core.Injector } ]; }; JadeIntegrationUtilsModule = __decorate([ core.NgModule({ declarations: [ JadeIntegrationUtilsComponent, CheckRoleDirective ], imports: [ common.CommonModule, platformBrowser.BrowserModule, http.HttpClientModule ], exports: [ http.HttpClientModule ], bootstrap: [JadeIntegrationUtilsComponent] }) ], JadeIntegrationUtilsModule); return JadeIntegrationUtilsModule; }()); exports.CheckRoleDirective = CheckRoleDirective; exports.DataService = DataService; exports.EventEmitterService = EventEmitterService; exports.GenericService = GenericService; exports.HttpStatusService = HttpStatusService; exports.HttpXHRService = HttpXHRService; exports.JadeIntegrationUtilsModule = JadeIntegrationUtilsModule; exports.StorageService = StorageService; exports.XHRManager = XHRManager; exports.loading = loading; exports.ɵa = JadeIntegrationUtilsComponent; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=jade-integration-utils.umd.js.map