prg-class
Version:
Clases genéricas utilizadas por microservicios Programamos SPA.
273 lines (272 loc) • 9.26 kB
JavaScript
;
function unixDate(aoDate) {
if (novaluePure(aoDate) || !fnIsValidDate(aoDate)) {
return 0;
}
return parseInt((aoDate.getTime() / 1000).toFixed(0));
}
/**
* Retorna el string de una expresión. Los objetos se convierten a string vacío.
*
* @param {*} aoValue Expresión que se convertirá a string.
* @returns {string} Retorna el string de una expresión. Los objetos se convierten a string vacío.
*/
function fnToString(aoValue) {
let lsRet = '';
try {
if (novaluePure(aoValue)) {
aoValue = '';
}
if (typeof aoValue === 'number') {
aoValue = aoValue.toString();
}
if (typeof aoValue === 'boolean') {
aoValue = aoValue === true ? '1' : '0';
}
if (typeof aoValue !== 'string') {
return '';
}
lsRet = aoValue.trim();
}
catch (error) {
fnLogError(`Error en trim: ${error}.`);
}
return lsRet;
}
/**
* Quita espacios a la izquierda y derecha de una expresión.
*
* @param {*} aoValue Expresión a la que se quitarán espacios.
* @returns {string} Quita espacios a la izquierda y derecha de una expresión.
*/
function trim(aoValue) {
return fnToString(aoValue).trim();
}
/**
* Retorna indicador de fecha válida.
*
* @param {Date} aoDate Fecha.
* @returns {boolean} Retorna true en caso de fecha válida, false en caso de fecha inválida.
*/
function fnIsValidDate(aoDate) {
if (Object.prototype.toString.call(aoDate) === '[object Date]') {
// it is a date
if (isNaN(aoDate.getTime())) { // d.valueOf() could also work
// date is not valid
return false;
}
else {
// date is valid
return true;
}
}
else {
// not a date
return false;
}
// return aoDate instanceof Date && !isNaN(aoDate.getTime());
}
/**
* Recibe un dato del tipo fecha. Retorna un string con formato: aaaa-mm-dd.
*
* @param {Date} aoDate Fecha.
* @param {boolean} abHourMin Indica si se deben incluir horas y minutos.
* @returns {string} Retorna un string con formato: aaaa-mm-dd.
*/
function fnGetDateString(aoDate, abHourMin) {
if (aoDate === null || aoDate === undefined) {
return '';
}
if (!fnIsValidDate(aoDate)) {
return '';
}
let lsRet = '';
const lsSep = '-';
const llM = aoDate.getMonth() + 1;
const llD = aoDate.getDate();
const llY = aoDate.getFullYear();
lsRet = llY + lsSep + llM + lsSep + llD;
if (abHourMin) {
lsRet += ` ${aoDate.getHours()}:${aoDate.getMinutes()}`;
}
return lsRet;
}
/**
* Muestra un error por consola.
*
* @param {string} asMsg Mensaje a mostrar por consola.
* @returns {string} Retorna string vacío.
*/
function fnLogError(asMsg) {
console.error(asMsg);
return '';
}
/**
* Sustituye caracteres en un texto. Si no recibe parámetros, cambia apóstrofe por un tilde (´).
*
* @param {string} asCharCambiar El caracter que se eliminará.
* @param {string} asCharCambio El caracter que se agregará.
* @param {string} asTxt Texto al cual se le modificarán caracteres.
* @returns {string} Texto con el caracter modificado. Si es nulo on indefinido, retorna string vacío.
*/
function fnStrReplace(asCharCambiar, asCharCambio, asTxt) {
if (asTxt === null || asTxt === undefined) {
return '';
}
if (asCharCambiar === null || asCharCambiar === undefined) {
asCharCambiar = '';
}
if (asCharCambio === null || asCharCambio === undefined) {
asCharCambio = '';
}
const lsType = typeof (asTxt);
if (lsType === 'object') {
if (Object.prototype.toString.call(asTxt) === '[object Date]') {
const loDt = asTxt;
const ldtFec = loDt;
asTxt = fnGetDateString(ldtFec, false);
}
else {
try {
asTxt = JSON.stringify(asTxt);
}
catch (error) {
fnLogError(`Error en fnStrReplace: ${error}.`);
}
}
}
if (lsType !== 'string') {
asTxt += '';
}
let lsRet = '';
for (let i = 0; i < asTxt.length; i++) {
let lsAux = asTxt.charAt(i);
if (lsAux === asCharCambiar) {
lsAux = asCharCambio;
}
lsRet += lsAux;
}
return lsRet;
}
/**
* Retorna boolean indicando si un valor es nulo o undefined.
* @param aoValue
*/
function novaluePure(aoValue) {
return (aoValue === undefined || aoValue === null);
}
/**
* Retorna boolean indicando si un valor es nulo o undefined.
* @param aoValue
*/
function novalue(aoValue) {
return novaluePure(aoValue) || aoValue === '';
}
/**
* Retorna número entero representado por una expresión.
*
* @param {*} aoValue Expresión que será evaluada para obtener valor numérico entero.
* @param {boolean} [abFtoChile=false] Indica si se debe interpretar la expresión como un número con formato chileno.
* @returns {number} Retorna número entero representado por una expresión.
*/
function intval(aoValue, abFtoChile = false) {
if (novalue(aoValue)) {
aoValue = '0';
}
if (typeof aoValue === 'object') {
return 0;
}
if (typeof aoValue === 'boolean') {
aoValue = aoValue === true ? 1 : 0;
}
let lsVal = aoValue + '';
if (abFtoChile) { // Es un formato de número con separador de decimales (coma) y signo peso.
lsVal = fnStrReplace('$', '', lsVal);
lsVal = fnStrReplace('.', '', lsVal);
lsVal = fnStrReplace(',', '.', lsVal);
}
let llRet = parseInt(lsVal, 10);
if (isNaN(llRet)) {
llRet = 0;
}
return llRet;
}
function fnReturn(asError, aoData = {}, alResponseCode) {
if (asError === undefined || asError === '') {
asError = null;
}
if (typeof asError === 'number') {
asError = asError.toString();
}
if (aoData === undefined || asError) {
aoData = null;
}
return { error: asError, json: aoData, s: alResponseCode };
}
function fnRetOk(aoRet, alCode = 200) {
return fnReturn(null, aoRet, alCode);
}
function fnRetErrBP(aoErr, alCode = 400) {
return fnReturn(aoErr, null, alCode);
}
function fnRetErrInt(aoErr, alCode = 500) {
return fnReturn(aoErr, null, alCode);
}
function middlewareIpUa(aoReq) {
let lsIp = '';
let lsToken = '';
let lsUserAgent = aoReq ? aoReq.headers['user-agent'] : '';
const lsUAO = lsUserAgent; // Guarda copia de useragent.
if (aoReq && aoReq.headers.via) {
lsIp = aoReq.headers['x-forwarded-for']; // Recupera ip de cliente (con proxy).
}
else {
lsIp = aoReq.connection.remoteAddress;
}
const lsAuth = aoReq && aoReq.headers ? trim(aoReq.headers.authorization) : '';
if (lsIp === undefined) {
lsIp = aoReq.connection.remoteAddress;
} // Recupera id de cliente (sin proxy).
const lsRIP = aoReq ? aoReq.headers['x-real-ip'] : ''; // IP para el caso de NGINX.
if (lsRIP) {
lsIp = lsRIP;
}
if (lsUserAgent !== '' && lsUserAgent !== undefined && lsUserAgent != null) {
let llAux = 0;
for (let i = 0; i < lsUserAgent.length; i++) {
const lsLet = lsUserAgent.slice(i, i + 1);
const llAsc = lsLet.charCodeAt(0);
const llAscCalc = llAsc * (i + 1);
llAux += llAscCalc;
}
lsUserAgent = llAux + '';
}
else {
lsUserAgent = '';
}
if (trim(lsAuth) !== '') {
const loTk = lsAuth.split(' ');
if (loTk && loTk.length === 2 && loTk[0] && loTk[0].toUpperCase() === 'BEARER' && loTk[1] && trim(loTk[1]) !== '') {
lsToken = loTk[1];
}
}
const loUPRM = { IP: lsIp, UA: lsUserAgent, UAO: lsUAO, TOKEN: lsToken };
return loUPRM;
}
module.exports = {
// fnStrpos, trim, intval, fnArrRemoveItemObj, fnContains, fnEndsWith, fnStartsWith, fnLeftCut, fnStrFill, fnStrRepeat,
// fnRightCut, fnSetTxtLen, substr, fnLong, fnBoolean, fnIsDate, strtoupper, sortByKey, novalue,
// fnSeparaComas, dateDiffInDays, fnStrReplace, fnRnd, fnLogError, fnLogInfo, formatMoney, floatval, fnGetDateToInsert,
// fnDateAddDays, fnGetWeekDate, fnFormatServer, fnGetIdFromArray, fnReturn, fnSql, fnGetRutDV, fnVeriRut, fnGetRut,
// fnVeriEmail, fnGetDateStringChile,
// fnDateAddMonth, fnCapitalyze, fnGetDateString, fnGetStringFromArray, fnGetTextMsg, fnToString, fnIsArray, fnStrReverse,
// fnSubstringCount, fnDateOnly, fnFixDec2, fnToNumberChile, fnVeriParam,
// fnGetMailParams, getDbParams, valDateParam, valNumParam, valStrParam, numberFormat, monthDiff, valBoolParam,
// getIds, mailText, decimals, multiply, getUuid, getPathTemp, getPathAssets, getPathFiles, getPathTimbre, getPathFirma,
// fnApos, fnRangeDateStr,
// hashCode, sortBy2Key, fnGetMeses,
fnRetOk, fnRetErrBP, fnRetErrInt, fnIsValidDate, fnGetDateString, fnLogError,
fnStrReplace, novaluePure, novalue, intval, fnReturn, fnToString, trim, middlewareIpUa,
unixDate,
// headerJson, getCallParams, getUrl, isGet, isDelete, isPost, isPut, isPatch,
};