#4 Re-estructuracion modulos, cambio de puerto, instalacion de paquetes,...

#4 Re-estructuracion modulos, cambio de puerto, instalacion de paquetes, implementacion autorizacion basica node express
parent bf99c85b
...@@ -6,6 +6,10 @@ const parameters = { ...@@ -6,6 +6,10 @@ const parameters = {
DBUSER: "mcafee_admin_territorios", DBUSER: "mcafee_admin_territorios",
DBPSSW: "HSuwshhuw43&%1253", DBPSSW: "HSuwshhuw43&%1253",
}, },
basicAuth:{
USER : 'userApi',
PASS : '34lq4od8usda'
}
}; };
module.exports.parameters = parameters; module.exports.parameters = parameters;
const express = require("express");
const szerCampaniaValidator = require("../validation_modules/validation"); const szerCampaniaValidator = require("../validation_modules/validation");
const userAgentValidator = require("express-useragent"); const { constants } = require("../config/constants");
const { array } = require("joi");
const app = express();
const jsonResponse = {}; const jsonResponse = {};
/*dbConn.con.query("SELECT * from template_css_relacion where tem_id = 1 and dco_id = 1 and tcr_tipo = 1 and tcr_entorno = 1 limit 1", function (err, result) { /*dbConn.con.query("SELECT * from template_css_relacion where tem_id = 1 and dco_id = 1 and tcr_tipo = 1 and tcr_entorno = 1 limit 1", function (err, result) {
if (err) throw err; if (err) throw err;
//console.log(`Result: ${JSON.stringify(result)}`); //console.log(`Result: ${JSON.stringify(result)}`);
});*/ });*/
/**
* Objeto de ayuda para respuestas http
*/
const HTTP_STATUS_CODE = {
OK: 200,
BAD_REQUEST: 400,
NOT_FOUND: 404,
ERROR: 500,
};
/**
* Objeto de ayuda para secciones html campaña
*/
const HTML_SECTIONS = {
HEAD: 1,
BODY: 2,
FOOTER: 3,
};
/**
* Objeto de ayuda para secciones html campaña
*/
const ACTIVE_STATUS = {
ACTIVE: 1,
NON_ACTIVE: 2,
};
/**
* Objeto de ayuda para secciones html campaña
*/
const DELETE_STATUS = {
DELETE: 1,
NON_DELETE: 0,
};
/**
* Objeto de ayuda para disposicion de contenido
*/
const CONTENT_DEVICE_DISPOSITION = {
MOBILE: 1,
DESKTOP: 2,
BOTH: 3,
};
const CONTENT_TYPE ={
TEXT: 1,
IMAGE: 2,
VIDEO: 3,
};
/**
* Se activa la utilizacion de json en express para esta instancia(Response)
*/
app.use(express.json());
/**
* Se activa la utilizacion de useragent en express para esta instancia(Response)
*/
app.use(userAgentValidator.express());
/** /**
* Definicion de clase para manejo de endpoints - Contenido * Definicion de clase para manejo de endpoints - Contenido
*/ */
class EndPointContenido { class EndPointContenido {
constructor(db) { constructor(db, serverApp) {
this.db = db; this.db = db;
this.serverApp = serverApp;
} }
getHtmlContent(path) { getHtmlContent(path) {
app.post(path, (req, res) => { this.serverApp.server.post(path, (req, res) => {
const validateCampania = new szerCampaniaValidator(); const validateCampania = new szerCampaniaValidator();
//Si falta el parametro uid, error 400 //Si falta el parametro uid, error 400
var { error } = validateCampania.validate(req.body); var { error } = validateCampania.validate(req.body);
if (error) { if (error) {
res.status(HTTP_STATUS_CODE.BAD_REQUEST).json({"error" : error.details[0].message}); res.status(constants.HTTP_STATUS_CODE.BAD_REQUEST).json({"error" : error.details[0].message});
return; return;
} }
...@@ -108,13 +39,13 @@ class EndPointContenido { ...@@ -108,13 +39,13 @@ class EndPointContenido {
//console.log("obteniendo campaña asociada..."); //console.log("obteniendo campaña asociada...");
const campania = await this.getCampaniaById([uid]); const campania = await this.getCampaniaById([uid]);
if(!campania || campania.length == 0) { if(!campania || campania.length == 0) {
res.status(HTTP_STATUS_CODE.NOT_FOUND).json({"error" : `El uid ${uid} no esta asociado a ninguna campaña.`}); res.status(constants.HTTP_STATUS_CODE.NOT_FOUND).json({"error" : `El uid ${uid} no esta asociado a ninguna campaña.`});
return; return;
} }
//console.log(campania[0].cam_id); //console.log(campania[0].cam_id);
const template = await this.getTemplateById([campania[0].tem_id]); const template = await this.getTemplateById([campania[0].tem_id]);
if(!template || template.length == 0) { if(!template || template.length == 0) {
res.status(HTTP_STATUS_CODE.NOT_FOUND).json({"error" : `La campaña uid ${uid} no tiene asociado ninguna plantilla de diseño.`}); res.status(constants.HTTP_STATUS_CODE.NOT_FOUND).json({"error" : `La campaña uid ${uid} no tiene asociado ninguna plantilla de diseño.`});
return; return;
} }
//console.log(template[0].tem_id); //console.log(template[0].tem_id);
...@@ -126,25 +57,25 @@ class EndPointContenido { ...@@ -126,25 +57,25 @@ class EndPointContenido {
jsonResponse.contenidoHead = await this.generateHtmlSection( jsonResponse.contenidoHead = await this.generateHtmlSection(
campania, campania,
template, template,
HTML_SECTIONS.HEAD, constants.HTML_SECTIONS.HEAD,
isMobile isMobile
); );
jsonResponse.contenidoBody = await this.generateHtmlSection( jsonResponse.contenidoBody = await this.generateHtmlSection(
campania, campania,
template, template,
HTML_SECTIONS.BODY, constants.HTML_SECTIONS.BODY,
isMobile isMobile
); );
jsonResponse.contenidoFooter = await this.generateHtmlSection( jsonResponse.contenidoFooter = await this.generateHtmlSection(
campania, campania,
template, template,
HTML_SECTIONS.FOOTER, constants.HTML_SECTIONS.FOOTER,
isMobile isMobile
); );
res.status(HTTP_STATUS_CODE.OK).send(jsonResponse); res.status(constants.HTTP_STATUS_CODE.OK).send(jsonResponse);
} }
async generateHtmlSection(campania, template, type, isMobile) { async generateHtmlSection(campania, template, type, isMobile) {
...@@ -209,8 +140,8 @@ class EndPointContenido { ...@@ -209,8 +140,8 @@ class EndPointContenido {
query = query =
query + query +
` WHERE cco_eliminado = ${DELETE_STATUS.NON_DELETE} ` WHERE cco_eliminado = ${constants.DELETE_STATUS.NON_DELETE}
and cco_estado = ${ACTIVE_STATUS.ACTIVE} and cco_estado = ${constants.ACTIVE_STATUS.ACTIVE}
and cam_id = ${campania[0].cam_id} and cam_id = ${campania[0].cam_id}
and sec_id = ${type} and sec_id = ${type}
`; `;
...@@ -218,11 +149,11 @@ class EndPointContenido { ...@@ -218,11 +149,11 @@ class EndPointContenido {
if (isMobile) if (isMobile)
query = query =
query + query +
` and dis_id in (${CONTENT_DEVICE_DISPOSITION.MOBILE}, ${CONTENT_DEVICE_DISPOSITION.BOTH}) `; ` and dis_id in (${constants.CONTENT_DEVICE_DISPOSITION.MOBILE}, ${constants.CONTENT_DEVICE_DISPOSITION.BOTH}) `;
else else
query = query =
query + query +
` and dis_id in (${CONTENT_DEVICE_DISPOSITION.DESKTOP}, ${CONTENT_DEVICE_DISPOSITION.BOTH}) `; ` and dis_id in (${constants.CONTENT_DEVICE_DISPOSITION.DESKTOP}, ${constants.CONTENT_DEVICE_DISPOSITION.BOTH}) `;
query = query + ` ORDER BY cco_fila ASC, cco_columna ASC;`; query = query + ` ORDER BY cco_fila ASC, cco_columna ASC;`;
//console.log(query); //console.log(query);
...@@ -234,19 +165,19 @@ class EndPointContenido { ...@@ -234,19 +165,19 @@ class EndPointContenido {
var html = ""; var html = "";
switch (contenido.cco_tipo) { switch (contenido.cco_tipo) {
case CONTENT_TYPE.TEXT: case constants.CONTENT_TYPE.TEXT:
html = ""; html = "";
html = this.getColumnaByDisposicion(contenido.cco_disposicion_nombre, contenido.cco_columna); html = this.getColumnaByDisposicion(contenido.cco_disposicion_nombre, contenido.cco_columna);
html = html + `<div id="texto_fil_${contenido.cco_fila}_con_${contenido.cco_id}" class="${contenido.cco_clase_css}" >${contenido.cco_contenido}</div>`; html = html + `<div id="texto_fil_${contenido.cco_fila}_con_${contenido.cco_id}" class="${contenido.cco_clase_css}" >${contenido.cco_contenido}</div>`;
html = html + '</div>'; html = html + '</div>';
break; break;
case CONTENT_TYPE.IMAGE: case constants.CONTENT_TYPE.IMAGE:
html = ""; html = "";
html = this.getColumnaByDisposicion(contenido.cco_disposicion_nombre, contenido.cco_columna); html = this.getColumnaByDisposicion(contenido.cco_disposicion_nombre, contenido.cco_columna);
html = html + `<img id="imagen_fil_${contenido.cco_fila}_con_${contenido.cco_id}" class="${contenido.cco_clase_css}" src="${contenido.cco_contenido}" />`; html = html + `<img id="imagen_fil_${contenido.cco_fila}_con_${contenido.cco_id}" class="${contenido.cco_clase_css}" src="${contenido.cco_contenido}" />`;
html = html + '</div>'; html = html + '</div>';
break; break;
case CONTENT_TYPE.VIDEO: case constants.CONTENT_TYPE.VIDEO:
html = ""; html = "";
html = this.getColumnaByDisposicion(contenido.cco_disposicion_nombre, contenido.cco_columna); html = this.getColumnaByDisposicion(contenido.cco_disposicion_nombre, contenido.cco_columna);
html = html + `<div id="video_fil_${contenido.cco_fila}_con_${contenido.cco_id}" class="${contenido.cco_clase_css} embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="${contenido.cco_contenido}"></iframe></div>`; html = html + `<div id="video_fil_${contenido.cco_fila}_con_${contenido.cco_id}" class="${contenido.cco_clase_css} embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="${contenido.cco_contenido}"></iframe></div>`;
...@@ -357,16 +288,6 @@ class EndPointContenido { ...@@ -357,16 +288,6 @@ class EndPointContenido {
} }
/**
* Definicion de funciones asociadas a endpoints
*/
function listenPort(port) {
app.listen(port, () => {
//console.log(`Escuchando en puerto ${port}...`);
});
}
/***/ /***/
module.exports.endPointContenidoManager = EndPointContenido; module.exports.endPointContenidoManager = EndPointContenido;
module.exports.listen = listenPort;
const app = require('./endpoints_modules/endpoints'); const serverApp = require('./appexpress_modules/app');
const endPoints = require('./endpoints_modules/endpoints');
const dbConn = require('./database_modules/database'); const dbConn = require('./database_modules/database');
//Trick para problema con eventListeners maximos /*Trick para problema con eventListeners maximos*/
require('events').EventEmitter.prototype._maxListeners = 100; require('events').EventEmitter.prototype._maxListeners = 100;
/** /**
* Se activa la conexion a la base de datos en modalidad pool * Se activa la conexion a la base de datos en modalidad pool
*/ **/
dbConn.con.getConnection((err, connection) => { dbConn.con.getConnection((err, connection) => {
if(err) { if(err) {
...@@ -15,14 +17,15 @@ dbConn.con.getConnection((err, connection) => { ...@@ -15,14 +17,15 @@ dbConn.con.getConnection((err, connection) => {
}); });
const endPointContenidoManager = new app.endPointContenidoManager(dbConn.con);
/* /*
* Solo en ambientes de desarrollo locales se coloca el puerto directamente al iniciar la aplicacion * Solo en ambientes de desarrollo locales se coloca el puerto directamente al iniciar la aplicacion
* en servidores, se debe obtener del objeto global "process" * en servidores, se debe obtener del objeto global "process"
*/ */
const port = process.env.PORT || 5000; const port = process.env.PORT || 5000;
app.listen(port); serverApp.listenPort(port);
const endPointContenidoManagerObj = new endPoints.endPointContenidoManager(dbConn.con, serverApp);
//Definicion de rutas para las api endpoint //Definicion de rutas para las api endpoint
endPointContenidoManager.getHtmlContent('/api/campania/obtener/contenido'); endPointContenidoManagerObj.getHtmlContent('/api/campania/obtener/contenido');
\ No newline at end of file \ No newline at end of file
...@@ -49,6 +49,14 @@ ...@@ -49,6 +49,14 @@
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
}, },
"basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"requires": {
"safe-buffer": "5.1.2"
}
},
"bignumber.js": { "bignumber.js": {
"version": "9.0.0", "version": "9.0.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
...@@ -179,6 +187,14 @@ ...@@ -179,6 +187,14 @@
"vary": "~1.1.2" "vary": "~1.1.2"
} }
}, },
"express-basic-auth": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/express-basic-auth/-/express-basic-auth-1.2.0.tgz",
"integrity": "sha512-iJ0h1Gk6fZRrFmO7tP9nIbxwNgCUJASfNj5fb0Hy15lGtbqqsxpt7609+wq+0XlByZjXmC/rslWQtnuSTVRIcg==",
"requires": {
"basic-auth": "^2.0.1"
}
},
"express-useragent": { "express-useragent": {
"version": "1.0.15", "version": "1.0.15",
"resolved": "https://registry.npmjs.org/express-useragent/-/express-useragent-1.0.15.tgz", "resolved": "https://registry.npmjs.org/express-useragent/-/express-useragent-1.0.15.tgz",
......
...@@ -10,7 +10,9 @@ ...@@ -10,7 +10,9 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"basic-auth": "^2.0.1",
"express": "^4.17.1", "express": "^4.17.1",
"express-basic-auth": "^1.2.0",
"express-useragent": "^1.0.15", "express-useragent": "^1.0.15",
"joi": "^17.2.1", "joi": "^17.2.1",
"mysql": "^2.18.1" "mysql": "^2.18.1"
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment