diff --git a/README.md b/README.md index a428acfe06f5c7a65e4d1b9baf79b9c9a107fb9f..f725fb2ee77989f40b289b7a89e0ce756e50dcb8 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,31 @@ # Webservice PInSIS -Webservice para disponibilizar os dados coletados pelos agentes do projeto PInSIS +Webservice that provide the data collected by agents of project PInSIS +## Dependencies: -## Dependências: - -- Use npm install para instalar as dependências do nodejs -- postgres >=9.0 (não necessariamente na mesma máquina) - - Deve-se criar usuário e banco de dados +- Use npm install to install the dependencies of nodejs +- postgres >=9.0 (not necessarily in the same computer) + - Must be created a Database and User - npm >=5.7.1 - nodejs >=v6.11.4 -## Uso +## Use -### Instale os módulos +### Install modules ```bash -npm install #Instala as dependências do node +npm install #Install node dependencies ``` -### Crie as relações +### Create the relatios -No diretório db/ há a documentação detalhada de como se deve criar/migrar as relações do banco de dados +There is a detailed documentation in the directory `db/` about how can be created/migrated the relations of the database -### Crie e altere o arquivo de configuração para acesso ao DB +### Create and alter the file of configuration to access database ```bash cp config.js.example config.js @@ -35,10 +34,10 @@ vim config.js ```bash -npm start #Executa o arquivo ./src/server.js com parâmetros defaults +npm start #Execute the file ./src/server.js with default parameters ``` -Os parâmetros possÃveis para executar o server.js são: +The possible parameters to execute `server.js` are: - [-c, --config] alternative configuration file (default: config.js) - [-p, --port] port where the server will listen to - [--insecure] allows session cookies to be passed around in insecure connections @@ -47,14 +46,14 @@ Os parâmetros possÃveis para executar o server.js são: - [-d, --daemon] start the server as a daemon - [--pid-file] path for the pid file when running as a daemon -## PossÃveis erros +## Possible errors -- Os principais problemas encontrados estão relacionados à conexão com o DB - Em caso de erros verifique se é possÃvel fazer conexão com o DB com o - psql por exemplo (no mesmo usuário em que está se executando os comandos) +- The main problems verified are relationed to the database connection. + In case of errors, verify if is possible do the connection with database + by `psql`command (in the same user that is in configuration file). -- Outro caso comum é tentar executar o serviço numa mesma porta em que outro - processo já está executando. Nesse caso um erro semelhante a - *Error: bind EADDRINUSE null:3000* será notificado. - Nesse caso tente alterar a porta em que o serviço será provido ou encerre - o outro processo. +- Another commum case is to try execute the service in a port that another + process is alredy executing. In this case a error similar to + `Error: bind EADDRINUSE null:3000` will be notified. + In this case, try alter the port that the service is provided or stop + the other process. diff --git a/config.js.example b/config.js.example index b2deb06c586c934a283170344e7321bf42f22b2e..85a20dea9b135afe720dddcebd133bf8b0cc5dfb 100644 --- a/config.js.example +++ b/config.js.example @@ -1,40 +1,11 @@ var config = module.exports = {}; config.db_config = { - user: 'user', - password: 'password', - database: 'dbname', - host: 'localhost', - port: 5432 + user: DB_USER, + password: DB_PASS, + database: DB_DBNAME, + host: DB_HOST, + port: DB_PORT }; -config.mail = { - port: 25 - , host: 'localhost' - , ignoreTLS: true - , secure: false - , from: 'noreply@simmc.c3sl.ufpr.br' -}; - -config.report_config = { - imagesPath: './reports/reports/images/' - , outputPath: './tmp/reports' -}; - -config.alert_config = { - alertsPath: '/home/simmc/simmc/scripts/alerts/' -}; - -config.fqdn = 'simmc.c3sl.ufpr.br'; - -config.agentVersion = 1.0; - -config.secret = '123mudar'; - -// Uncomment to enable memcached -// -// config.memcached = { -// server: 'localhost:11211', -// options: { retries: 1, timeout: 1000, poolSize: 1 }, -// lifetime: 3600 // 1 hour in seconds -// }; +config.agentVersion = 0.0; diff --git a/db/README.md b/db/README.md index 23812a1741ad507daebdd4b735615c728142f0ac..42b5b842f42a9d9955954eea578fe4d63d9d0c3b 100644 --- a/db/README.md +++ b/db/README.md @@ -1,44 +1,45 @@ # Create/Migrate DB PInSIS -Módulo para criar/migrar as relações do banco de dados do projeto PInSIS +Module to create/migrate the relations of the database of project PInSIS -Este projeto utiliza o [node-pg-migrate](https://github.com/salsita/node-pg-migrate). +This subproject utilize the [node-pg-migrate](https://github.com/salsita/node-pg-migrate). -## Exemplo de uso: +## Use example: ```bash -DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate up # Cria todos os schemas -DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate down # Cria o banco de dados +DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate up # Create all schemas +DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate down # Undo the last migration ``` -Observe que é necessário definir uma variável de ambiente ao executar os comandos acima. -Para uma documentação mais completa e métodos alternativos de utilizar os comandos consule [node-pg-migrate CLI Usage](https://github.com/salsita/node-pg-migrate/blob/master/docs/cli.md) +Observe that is necessary to define a env variable by the executation of the above commands. +There is a documentation more complete and alternative methods to utilize the library in [node-pg-migrate CLI Usage](https://github.com/salsita/node-pg-migrate/blob/master/docs/cli.md). -## Camadas -Observe que quando os migrates ups executados no exemplo anterior passarão por todas as migrações existentes em ./migrations e criarão os modelos na ordem cronológica. -No caso dos migrates downs, cada execução irá "descer uma camada" em relação à s migrações. +## Layers -Consulte a documentação original para ver métodos alternativos para simplificar o uso. +Observe that when the `migrates up`commands are executed in the previous example, all the migrations in `./migrations` will be used to create the database in cronologic order. +In case of `migrate down`commands, each execution will "down one layer" in relation of the migrations. -## Migrar o banco +You can find in the original documentation alternative methods to simplify the use. + +## Migrate the database ```bash -# Esses comandos criarão modelos no diretório /migrations +# This commands will create models in the directory ./migrations -# Por questões de padronização, adotou-se que os nomes das migrações -# teriam espacamento substituido por _ -# por exemplo: add_table_1 +# Because of standartion, the migrations name will use _ instead of space +# by instance: add_table_1 # alter_colum_x_from_table2 -npm run migrate create nome da migracao -npm run migrate create migration4 -npm run migrate create migration5 +Examples + +npm run migrate create add_table_agent +npm run migrate create add_views_agentuses ``` -## PossÃveis erros +## Possible errors -- Os principais problemas encontrados estão relacionados à conexão com o DB - Em caso de erros verifique se é possÃvel fazer conexão com o DB com o - psql por exemplo (no mesmo usuário em que está se executando os comandos) +- The main problems verified are relationed to the database connection. + In case of errors, verify if is possible do the connection with database + by `psql`command (in the same user that is in configuration file). diff --git a/db/package.json b/db/package.json index f99f5de7d3811595cf41ae42e2103a6b98387552..c934cca183b03d4ad0ec3d42e3f07967fc928347 100644 --- a/db/package.json +++ b/db/package.json @@ -4,8 +4,11 @@ "description": "", "main": "", "dependencies": { - "node-pg-migrate": "^3.0.0", - "pg": "^7.4.1" + "migration": "^0.3.0", + "node-pg-migrate": "^3.1.1", + "npm": "^6.0.1", + "pg": "^7.4.1", + "runner": "^1.0.4" }, "devDependencies": {}, "scripts": { diff --git a/src/routes/data.js b/src/routes/data.js index de37abe46e687bfbdca9ad30de3d7c73b2f5b4e5..3098715abd55115a6771fd22458780b119fd434a 100644 --- a/src/routes/data.js +++ b/src/routes/data.js @@ -60,13 +60,17 @@ function querie_db(req, q, callback){ conn.query(q.toParam().text,q.toParam().values, function(err,data,fields){ done(); - if (err) callback(err, null); + if (err){ + callback(err, null); + return; + } callback(null, data) }); }); } catch(err){ - callback(err,null); + done(); + callback(err,null); } } @@ -112,19 +116,9 @@ module.exports = function(agentVersion) { //Access the correct view //Group entries that was considered executed and count the total uses - if(req.query['executed'] != null) table+="ByStatus"; + if(req.query['executed'] != null) table+="bystatus"; q = qb.select_between(table,parameters); - - - - - if(req.query['fk_agent']){ - q = qb.filter_query(q,{"fk_agent": parseInt(req.query['fk_agent'])}); - } - - - break; case 'Agent': @@ -134,50 +128,53 @@ module.exports = function(agentVersion) { q = qb.select(table,parameters); break; } + + if(req.query['id']){ + q = qb.filter_query(q,{"id": parseInt(req.query['id'])}); + } } catch(err){ console.log(err); return res.status(500).json({error: 'Invalid fields'}); } - - - - - querie_db(req, q, function(err, data) { - if (err) { - req.log.error(err); - return res.status(500).json({error: 'db_connection_failed'}); - } + + querie_db(req, q, function(err, data) { + + if (err || !data) { + req.log.error(err); + return res.status(500).json({error: 'db_connection_failed'}); + } // Create two class of uses in json: sus and not_sus - if(table in tables_uses){ - data.rows = data.rows.sort(function(a,b){ - return new Date(a.date) - new Date(b.date); - }); - - - var sus = data.rows.filter(function(x){ - return x.is_sus; - }); - var not_sus = data.rows.filter(function(x){ - return !x.is_sus; - }); - - return res.status(200).json( - { - "sus": sus, - "not_sus": not_sus - } - ); - - } - else{ - return res.status(200).json(data.rows); - } - - }); - } + if(table in tables_uses){ + data.rows = data.rows.sort(function(a,b){ + return new Date(a.date) - new Date(b.date); + }); + + + var sus = data.rows.filter(function(x){ + return x.is_sus; + }); + var not_sus = data.rows.filter(function(x){ + return !x.is_sus; + }); + + return res.status(200).json( + { + "sus": sus, + "not_sus": not_sus + } + ); + + } + else{ + return res.status(200).json(data.rows); + } + + }); + + } }; }