UNPKG

zeev-form-js

Version:

Repositório com diversos códigos reaproveitáveis e estruturados para utilizar em projetos.

118 lines (106 loc) 4.51 kB
import { ZeevResources } from "./zeev-form-resources.js"; export var ZeevIntegrations = { Settings: { TimeOut: 200, IsDebug: isDebug, Environment: environment }, DataSources: { GetCepData: { name: 'P00X - Get CEP Data', value: 'https://viacep.com.br/ws/{params}/json/', Dev: '../{CAMINHO RELATIVO DA INTEGRAÇÃO DO ZEEV}', Hml: '../{CAMINHO RELATIVO DA INTEGRAÇÃO DO ZEEV}', Prd: '../{CAMINHO RELATIVO DA INTEGRAÇÃO DO ZEEV}' } }, BuildParamsToGetDataSource: ((params) => { var resultParams = '?'; Object.entries(params).forEach((field, index) => { resultParams += index > 0 ? '&' : ''; resultParams += field[0] + "=" + field[1]; }); return resultParams; }), GetUrlDataSource: ((dataSource) => { var urlDataSource = ''; if (dataSource.value) urlDataSource = dataSource.value; else { switch (ZeevIntegrations.Settings.Environment.toUpperCase()) { case 'DEV': urlDataSource = dataSource.valueDev; break; case 'HML': urlDataSource = dataSource.valueHml; break; case 'PRD': urlDataSource = dataSource.valuePrd; break; } } return urlDataSource; }), Functions: { ExecuteDataSource: (async (dataSource, params, methodVerb = "GET") => { if(ZeevResources.NativeResources.Loader) ZeevResources.NativeResources.Loader.element.style.display = 'block'; var result = ''; let strParams = ''; var myHeaders = new Headers(); var urlDataSource = ZeevIntegrations.GetUrlDataSource(dataSource); var requestOptions = ''; if (methodVerb.toUpperCase() == 'GET') { requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; if (params) strParams = ZeevIntegrations.BuildParamsToGetDataSource(params); } if (methodVerb.toUpperCase() == 'POST') { requestOptions = { method: 'POST', headers: myHeaders, redirect: 'follow', body: JSON.stringify(params) }; } var url = urlDataSource + (strParams == '?' ? '' : strParams); await fetch(url, requestOptions) .then(response => { const contentType = response.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return response.json().then(data => { return data; }).catch(error => { console.log(`Fonte de dados: ${dataSource.name}`); throw Error(error); }); } else { return response.text().then(text => { console.log(`Fonte de dados: ${dataSource.name}`); throw Error(text); }); } }) .then(rst => { if (rst != null) result = rst.success.length > 1 ? rst.success : rst.success[0]; else result = null; }) .catch(error => { if(ZeevResources.NativeResources.Loader) ZeevResources.NativeResources.Loader.element.style.display = 'none'; cryo_alert(`Erro na consulta da Fonte de dados <b>' + ${dataSource.name} + '</b>', ${error}`); console.log(`Fonte de dados: ${dataSource.name}, ${error}`); throw Error(error); }); if(ZeevResources.NativeResources.Loader) ZeevResources.NativeResources.Loader.element.style.display = 'none'; return result; }), } }