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!).

832 lines (816 loc) 29 kB
import { __decorate } from 'tslib'; import { EventEmitter, ɵɵdefineInjectable, Injectable, ɵɵinject, ElementRef, Renderer2, Input, Directive, Component, Injector, NgModule } from '@angular/core'; import { HttpClient, HttpClientModule } from '@angular/common/http'; import { Router } from '@angular/router'; import { CommonModule } from '@angular/common'; import { BrowserModule } from '@angular/platform-browser'; let EventEmitterService = class EventEmitterService { static get(nomeEvento) { if (!this.emitters[nomeEvento]) this.emitters[nomeEvento] = new EventEmitter(); return this.emitters[nomeEvento]; } }; EventEmitterService.emitters = {}; EventEmitterService.ɵprov = ɵɵdefineInjectable({ factory: function EventEmitterService_Factory() { return new EventEmitterService(); }, token: EventEmitterService, providedIn: "root" }); EventEmitterService = __decorate([ Injectable({ providedIn: 'root' }) ], EventEmitterService); let StorageService = class StorageService { constructor() { } static get(index) { const obj = localStorage.getItem(index); return obj ? JSON.parse(obj) : null; } static set(index, object) { localStorage.setItem(index, JSON.stringify(object)); } static getSession(index) { const obj = sessionStorage.getItem(index); return obj ? JSON.parse(obj) : null; } static setSession(index, object) { sessionStorage.setItem(index, JSON.stringify(object)); } static getTemp() { const obj = sessionStorage.getItem('temp'); return obj ? JSON.parse(obj) : null; } static setTemp(object) { sessionStorage.setItem('temp', JSON.stringify(object)); } static clearTemp() { sessionStorage.removeItem('temp'); } static clear() { localStorage.clear(); sessionStorage.clear(); } static APIMaps() { return "AIzaSyBiQp1xNr0h8WLV_6OlbMu2E83ezjShoAk"; } }; StorageService.ɵprov = ɵɵdefineInjectable({ factory: function StorageService_Factory() { return new StorageService(); }, token: StorageService, providedIn: "root" }); StorageService = __decorate([ Injectable({ providedIn: 'root' }) ], StorageService); let HttpStatusService = class HttpStatusService { constructor(http) { this.http = http; this._url = ''; this._AUTH = "auth"; this._options = { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, responseType: "json" }; } configure(url) { this._url = url; } set_token(auth) { StorageService.set(this._AUTH, "Bearer " + auth); this._options.headers.Authorization = (this.get_token()) ? StorageService.get(this._AUTH) : null; } get_token() { return StorageService.get(this._AUTH); } get(endpoint) { return this.http.get(this._url + endpoint, this._options).toPromise(); } get_file(endpoint) { this.options.responseType = "blob"; return this.http.get(this._url + endpoint, this._options).toPromise(); } post(endpoint, body) { return this.http.post(this._url + endpoint, body, this._options).toPromise(); } formData(endpoint, body) { delete this._options.headers["Content-Type"]; return this.http.post(this._url + endpoint, body, this._options).toPromise(); } put(endpoint, body) { return this.http.put(this._url + endpoint, body, this._options).toPromise(); } delete(endpoint) { return this.http.delete(this._url + endpoint, this._options).toPromise(); } set options(option) { this._options = option; } get options() { return this._options; } default_options() { this._options = { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, responseType: "json" }; } }; HttpStatusService.ctorParameters = () => [ { type: HttpClient } ]; HttpStatusService.ɵprov = ɵɵdefineInjectable({ factory: function HttpStatusService_Factory() { return new HttpStatusService(ɵɵinject(HttpClient)); }, token: HttpStatusService, providedIn: "root" }); HttpStatusService = __decorate([ Injectable({ providedIn: 'root' }) ], HttpStatusService); let GenericService = class GenericService { constructor(http, router) { this.http = http; this.router = router; this._auth = "Authentication"; } /** * configureHttp */ configureHttp(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) */ get(endpoint, queryParams) { let 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) */ get_file(endpoint, queryParams) { let 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) */ get_any(endpoint, queryParams) { let 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); } getById(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 */ post(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 */ formData(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 */ put(body, endpoint) { return this.http.put('/' + endpoint, body); } delete(id, endpoint) { return this.http.delete('/' + endpoint + '/' + id); } set_token(auth) { this.http.set_token(auth); } get_token() { return this.http.get_token(); } get options() { return this.http.options; } set options(options) { this.http.options = options; } default_options() { this.http.default_options(); } set auth(auth) { StorageService.set(this._auth, auth); this.set_token(auth); } get auth() { return StorageService.get(this._auth); } downloadFile(data) { const blob = new Blob([data]); const url = window.URL.createObjectURL(blob); window.open(url); } }; GenericService.ctorParameters = () => [ { type: HttpStatusService }, { type: Router } ]; GenericService.ɵprov = ɵɵdefineInjectable({ factory: function GenericService_Factory() { return new GenericService(ɵɵinject(HttpStatusService), ɵɵinject(Router)); }, token: GenericService, providedIn: "root" }); GenericService = __decorate([ Injectable({ providedIn: 'root' }) ], GenericService); class HttpMethod { } HttpMethod.GET = "get"; HttpMethod.POST = "post"; HttpMethod.PUT = "put"; HttpMethod.DELETE = "delete"; HttpMethod.OPTIONS = "options"; HttpMethod.PATCH = "patch"; class HttpXHRService { constructor(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; } } set_token(auth) { StorageService.set(this._AUTH, 'Bearer ' + auth); } get_token() { return StorageService.get(this._AUTH); } get(endpoint) { this._xhttp.open(HttpMethod.GET, this._standard_url + endpoint); return this._send_request(); } get_file(endpoint) { this._xhttp.open(HttpMethod.GET, this._standard_url + endpoint); return this._send_request(); } post(endpoint, body) { this._xhttp.open(HttpMethod.POST, this._standard_url + endpoint); return this._send_request(body); } formData(endpoint, body) { this._xhttp.open(HttpMethod.POST, this._standard_url + endpoint); return this._send_request(body); } put(endpoint, body) { this._xhttp.open(HttpMethod.PUT, this._standard_url + endpoint); return this._send_request(body); } delete(endpoint) { this._xhttp.open(HttpMethod.DELETE, this._standard_url + endpoint); return this._send_request(); } _send_request(data = null, timeout = 60000) { const token = this.get_token(); this._xhttp.setRequestHeader('Content-Type', 'application/json'); for (let index = 0; index < this._headers.length; index++) { const 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((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); } }); } } class XHRManager { constructor(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) */ get(endpoint, queryParams) { let 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) */ get_file(endpoint, queryParams) { let 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) */ get_any(endpoint, queryParams) { let new_endpoint = ''; if (queryParams) { new_endpoint = '/' + endpoint + '?' + queryParams; } else { new_endpoint = '/' + endpoint; } return this.http_xhr.get(new_endpoint); } getById(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 */ post(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 */ formData(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 */ put(body, endpoint) { return this.http_xhr.put('/' + endpoint, body); } delete(id, endpoint) { return this.http_xhr.delete('/' + endpoint + '/' + id); } set_token(auth) { this.http_xhr.set_token(auth); } get_token() { return this.http_xhr.get_token(); } set auth(auth) { StorageService.set(this._auth, auth); this.set_token(auth); } get auth() { return StorageService.get(this._auth); } downloadFile(data) { const blob = new Blob([data]); const url = window.URL.createObjectURL(blob); window.open(url); } } let CheckRoleDirective = class CheckRoleDirective { constructor(el, renderer) { let user = StorageService.getSession('user'); setTimeout(() => { if (user !== null && this.roles.indexOf(user.role.sigla) == -1) { renderer.setStyle(el.nativeElement, 'display', 'none'); } }, 100); } }; CheckRoleDirective.ctorParameters = () => [ { type: ElementRef }, { type: Renderer2 } ]; __decorate([ Input('checkRole') ], CheckRoleDirective.prototype, "roles", void 0); CheckRoleDirective = __decorate([ Directive({ selector: '[jiuCheckRole]' }) ], CheckRoleDirective); function loading(flag) { return function (target, key, descriptor) { let originalMethod = descriptor.value; descriptor.value = function (...args) { this[flag] = true; let result = originalMethod.apply(this, args); if (result) { result.next = (val) => { this[flag] = false; return result._next(val); }; result.error = (err) => { //console.log(err); this[flag] = false; return result._error(err); }; } else { this[flag] = false; } return result; }; return descriptor; }; } class DataService { constructor(api_url, endpoint) { this._endpoint = ""; this.xMan = new XHRManager(api_url, endpoint); this.element_list = new Array(); this.loading = false; this._endpoint = endpoint; } remove_e_query(query) { query = query.startsWith("&") ? query.replace(query.charAt(0), "") : query; return query; } getById(id, callbackHandler) { this.loading = true; this.xMan.getById(id, this._endpoint) .then((result) => { this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => this.loading = false); } bind_results(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(); } get(filter, callbackHandler, pagination = false) { this.loading = true; let query = this.serialize_query(filter) + (pagination ? '&' + this.get_pagination_query() : ''); console.log(query); this.xMan.get(this._endpoint, query) .then((result) => { this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => this.loading = false); } getAll(callbackHandler, pagination = false) { this.loading = true; let pagination_query = (pagination ? this.get_pagination_query() : ''); console.log(pagination); this.xMan.get(this._endpoint, pagination_query) .then((result) => { this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => this.loading = false); } next(filter) { this.page += 1; this.get(filter, true); } previous(filter) { if (this.page > 1) this.page -= 1; this.get(filter, true); } /** * calls a http get to not configured endpoint * * @param endpoint another endpoint */ get_by_endpoint(endpoint, callbackHandler, query_params, pagination = false) { this.loading = true; console.log(pagination); this.xMan.get(endpoint + (pagination ? this.get_pagination_query() : '')) .then((result) => { this.bind_results(result); if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => 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 */ post(body, callbackHandler) { this.loading = true; this.xMan.post(this.remove_resource(body), this._endpoint) .then((result) => { this.results = result; if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => 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 */ create(body, callbackHandler) { this.loading = true; this.xMan.post(this.remove_resource(body), this._endpoint) .then((result) => { this.results = result; if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => 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 */ update(body, callbackHandler) { this.loading = true; this.xMan.put(this.remove_resource(body), this._endpoint) .then((result) => { this.results = result; if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => 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 */ put(body, callbackHandler) { this.loading = true; this.xMan.put(body, this._endpoint) .then((result) => { this.results = result; if (callbackHandler) callbackHandler(result); }) .catch((error) => this.showError(error)) .finally(() => 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 */ delete(id, callbackHandler) { this.loading = true; this.xMan.delete(id, this._endpoint) .then((results) => { if (results.target) { if (callbackHandler) callbackHandler(results); } else { alert("Ocorreu um erro!"); } }) .catch((error) => this.showError(error)) .finally(() => this.loading = false); } /** * Set's Authentication bearer * @param auth strings containing authentication bearer */ set_auth(auth) { this.xMan.set_token(auth); } get_auth() { return this.xMan.get_token(); } get_pages_array() { this.page_array = new Array(); let pagesCount = this.itemsCount / this.fetch; for (let index = 1; index <= pagesCount; index++) { this.page_array.push(index); } } get_pagination_query() { return "fetch=" + this.fetch + "&page=" + this.page; } show_success(msg) { alert(msg || 'Saved with success'); } showError(error) { console.log("***API ERROR REPORT***"); console.log(error); console.log("--------------------"); } logout() { StorageService.clear(); this.xMan.auth = ''; window.location.reload(); } serialize_query(obj) { var str = []; for (var p in obj) { if (typeof obj[p] === 'object') { for (const key in obj[p]) { if (p == 'resource') continue; if (Object.prototype.hasOwnProperty.call(obj[p], key)) { const 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; } auto_bind(result, target) { for (var p in result) { if (target.hasOwnProperty(p) && result.hasOwnProperty(p)) { target[p] = result[p]; } } } remove_resource(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; } static normalizeString(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"; let JadeIntegrationUtilsComponent = class JadeIntegrationUtilsComponent { constructor() { } ngOnInit() { } }; JadeIntegrationUtilsComponent = __decorate([ Component({ selector: 'JadeIntegrationUtilsComponent', template: `` }) ], JadeIntegrationUtilsComponent); let InjectorInstance; let JadeIntegrationUtilsModule = class JadeIntegrationUtilsModule { constructor(_injector) { this._injector = _injector; InjectorInstance = this._injector; } }; JadeIntegrationUtilsModule.ctorParameters = () => [ { type: Injector } ]; JadeIntegrationUtilsModule = __decorate([ NgModule({ declarations: [ JadeIntegrationUtilsComponent, CheckRoleDirective ], imports: [ CommonModule, BrowserModule, HttpClientModule ], exports: [ HttpClientModule ], bootstrap: [JadeIntegrationUtilsComponent] }) ], JadeIntegrationUtilsModule); /* * Public API Surface of ng-shared-utils */ /** * Generated bundle index. Do not edit. */ export { CheckRoleDirective, DataService, EventEmitterService, GenericService, HttpStatusService, HttpXHRService, InjectorInstance, JadeIntegrationUtilsModule, StorageService, XHRManager, loading, JadeIntegrationUtilsComponent as ɵa }; //# sourceMappingURL=jade-integration-utils.js.map