Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jose-souza #23

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.env
/node_modules
/.idea
yarn.lock
package-lock.json
29 changes: 29 additions & 0 deletions doc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# NODE JS


## Para rodar este projeto
```bash
$ npm install
$ node run start
```
Acesssar pela url: http://localhost:8000/ #neste caso a porta esta a padrão, mais pode ser alterada se necessário, PS: o link para acesso é mostrado quando o comardo anterior é executado.



## Acesso
- Utilizando o POSTMAN, Insomnia ou alguma outra ferramente do tipo, deve ser feita uma requisição 'POST'.
- url: http://localhost:3000, passando como parametro obrigatório uma matriz quadrada.
- Variável referente a matriz que deve ser passada na requisição deve-se chamar 'matrix'.

## Exemplo da Variável
{
"matrix": [
[1, 2, 3, 6],
[4, 5, 6, 3],
[9, 5, 7, 0],
[4, 8, 9, 0]
]
}

## Observação
- A aplicação esta mapeada para a porta 3000.
31 changes: 31 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "backend-challenge",
"version": "1.0.0",
"description": "Esse repositório é o nosso desafio para avaliar o quão bom desenvolvedor back-end você é.",
"main": "src/server.js",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.15.4",
"express-validator": "^6.9.2",
"mongoose": "^5.0.16",
"redis": "^2.8.0"
},
"devDependencies": {
"nodemon": "^1.17.3"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon"
},
"repository": {
"type": "git",
"url": "git+https://github.com/jlaurosouza/backend-challenge.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/jlaurosouza/backend-challenge/issues"
},
"homepage": "https://github.com/jlaurosouza/backend-challenge#readme"
}
16 changes: 16 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

const router = express.Router();

//Rotas
const index = require('./routes/index');
const homeRoute = require('./routes/homeRoute');

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.use('/', homeRoute);

module.exports = app;
33 changes: 33 additions & 0 deletions src/controllers/homeController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
exports.get = (req, res, next) => {
res.status(200).send('utiliza a rota post');
};

exports.post = (req, res, next) => {
try {
const { body } = req;
const { matrix } = body;

let lengthMatrix = matrix.length;
let diagonalLeftToRight = 0;
let diagonalRightToLeft = 0;

for(let i = 0; i < matrix.length; i++){
diagonalLeftToRight = diagonalLeftToRight + matrix[i][i];
diagonalRightToLeft = diagonalRightToLeft + matrix[i][--lengthMatrix];
}

const diff = diagonalLeftToRight - diagonalRightToLeft;


return res.json({
success: 200,
data: `A diferença da matriz é ${diff}`
});
} catch (e) {
console.log(e)
return res.json({
error: 400,
data: 'Não foi possível identificar a diferença da matriz.'
});
}
}
12 changes: 12 additions & 0 deletions src/helpers/validatorHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const validationResult = require('express-validator').validationResult;

module.exports = {
check(req, res, next) {
const errors = validationResult(req);

if (!errors.isEmpty()) {
return res.status(400).json({ message: errors.array() });
}
return next();
}
}
10 changes: 10 additions & 0 deletions src/routes/homeRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const express = require('express');
const router = express.Router();
const homeController = require('../controllers/homeController');
const homeValidator = require('../validators/homeValidator');
const ValidatorHelper = require('../helpers/validatorHelper');

router.get('/', homeController.get);
router.post('/', homeValidator.postRules, ValidatorHelper.check, homeController.post);

module.exports = router;
12 changes: 12 additions & 0 deletions src/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

const express = require('express');
const router = express.Router();

router.get('/', function (req, res, next) {
res.status(200).send({
title: "Node Express API",
version: "0.0.1"
});
});

module.exports = router;
20 changes: 20 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const app = require('./app');

const port = normalizaPort(process.env.PORT || '3000');

function normalizaPort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}

if (port >= 0) {
return port;
}

return false;
}

app.listen(port, function () {
console.log(`app listening on port ${port}`)
})
19 changes: 19 additions & 0 deletions src/validators/homeValidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const check = require('express-validator').check;

module.exports = {
postRules:[
check('matrix')
.exists().withMessage("Por favor informa uma matriz quadrada")
.custom((matrix) => {
return new Promise((resolve, reject) => {
const lengthMatrix = matrix.length;
matrix.map(mat => {
if (mat.length != lengthMatrix){
reject();
}
})
resolve();
});
}).withMessage("A matriz não é quadrada, favor nformar uma outra matriz")
]
};