Skip to content

Commit

Permalink
Merge pull request #67 from mia-ajuda/develop
Browse files Browse the repository at this point in the history
[RELEASE] Mia Ajuda Toyger 1.0.1
  • Loading branch information
darmsDD authored Jul 22, 2020
2 parents f655f7f + 117a258 commit 6fdb054
Show file tree
Hide file tree
Showing 47 changed files with 2,363 additions and 2,287 deletions.
7 changes: 5 additions & 2 deletions .env-example
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
DATABASE_URL=
NODE_ENV=[development|production]
LATITUDE_ENV=
LONGITUDE_ENV=
SENTRY_DSN=
NODE_ENV=development
DATABASE_URL=mongodb://mongo/miaAjudaDB
17 changes: 15 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,23 @@
"ecmaVersion": 2018
},
"rules": {
"indent": ["error", 4],
"indent": [
"error",
2
],
"semi": [
"error",
"always"
],
"no-underscore-dangle": 0,
"no-param-reassign": 0,
"max-len": ["error", { "code": 120 }],
"no-console": 0,
"max-len": [
"error",
{
"code": 120
}
],
"no-useless-catch": 0,
"class-methods-use-this": 0
}
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ jspm_packages/

# Firebase config
src/config/firebaseConfig.js
src/config/firebaseConfig-dev.js

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
Expand Down
81 changes: 69 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,74 @@
# Mia Ajuda - Backend
<p align="center">
<img src="https://i.imgur.com/5wtqEys.png" alt="Logo Mia Ajuda" width="50%"/>
</p>

<a href="https://mia-ajuda.github.io/Documentation/#/" target="_blank"><img src="https://img.shields.io/badge/Mia%20Ajuda-2020.1-purple"></a>
<p align="center">
<a href="https://play.google.com/store/apps/details?id=com.unb.miaajuda" target="_blank"><img src="https://img.shields.io/badge/Mia%20Ajuda-Google%20Play-yellow"></a>
<a href="https://miaajuda.netlify.app/" target="_blank"><img src="https://img.shields.io/badge/Mia%20Ajuda-Website-blue"></a>
<a href="https://mia-ajuda.github.io/Documentation/#/" target="_blank"><img src="https://img.shields.io/badge/Mia%20Ajuda-Docs-purple"></a>
<a href="https://github.com/mia-ajuda/Backend/pulls" target="_blank"><img src="https://img.shields.io/github/issues-pr/mia-ajuda/Backend?color=red&label=Pull%20Requests"></a>
</p>

## Rode com Docker
## Rode o Backend com Docker

Para executar localmente a aplicação, proceda com os seguintes passos:
### Dependências

1. Instale o Docker [neste link](https://docs.docker.com/install/linux/docker-ce/ubuntu/).
2. Instale o Docker Compose [neste link](https://docs.docker.com/compose/install/).
3. Pegue o arquivo firebaseConfig.js do drive na pasta firebase e coloque-o dentro da pasta config do projeto.
4. Crie um arquivo .env e dentro dele crie 2 váriaveis de ambiente LATITUDE_ENV= e LONGITUDE_ENV=
5. Coloque a latitude e longitude de sua casa nas variáveis de ambiente.
6. Na pasta principal do projeto, construa e inicialize a aplicação com o comando: `sudo docker-compose -f docker-compose.yml up --build`.
7. O backend estará disponível em: `http://localhost:8000/`.
Inicialmente, instale localmente as seguintes dependências:

* Observação: por padrão, o docker-compose iniciará a API com `yarn start`.
1. Instale o [Docker](https://docs.docker.com/install/linux/docker-ce/ubuntu/);
2. Instale o [Docker Compose](https://docs.docker.com/compose/install/).

### Arquivos de Configuração

1. A aplicação utiliza-se de autenticação por meio do [firebase](https://firebase.google.com/), logo, insira na pasta `src/config` o arquivo `firebaseConfig-dev.js`. O arquivo de configuração obtido do firebase deve apresentar a seguinte fisionomia:

```js
const config = {
type: '',
project_id: '',
private_key_id: '',
private_key: '',
client_email: '',
client_id: '',
auth_uri: '',
token_uri: '',
auth_provider_x509_cert_url: '',
client_x509_cert_url: '',
};

const databaseURL = '';

module.exports = {
config,
databaseURL,
};
```

2. Crie um arquivo `.env` na raiz do projeto e preencha as seguintes variáveis de ambiente:

```env
LATITUDE_ENV=
LONGITUDE_ENV=
SENTRY_DSN=
NODE_ENV=development
DATABASE_URL=mongodb://mongo/miaAjudaDB
```

* O preenchimento do serviço de monitoramento de erros ([Sentry](https://sentry.io/)) é opcional. A latitude e a longitude serão utilizadas para popular exemplos de pedido de ajuda próximos a essa coordenada.

### Inicialização do Projeto

1. Na pasta principal do projeto, construa e inicialize a aplicação com o comando:

```bash
sudo docker-compose -f docker-compose.yml up --build
```

2. O backend estará disponível em: `http://localhost:8000/`.

### Configuração do ESLint

1. Instale globalmente o pacote do eslint: `npm i -g eslint`;
2. Na raiz do projeto, verifique a corretude do código com `eslint . --ext .js`; ou
3. Configure uma extensão no seu editor de texto preferido (exemplo: [VSCode - ESLINT](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint));
4. Abra o seu editor de texto na raiz do projeto `/Backend` e comece a desenvolver.
28 changes: 16 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
require("dotenv").config();
require('dotenv').config();

const bodyParser = require("body-parser");
const cors = require("cors");
const express = require("express");
const http = require("http");
const setRoutes = require("./src/routes/BaseRoutes");
const dailySchedule = require("./src/utils/schedule");
const { setupWebsocket } = require("./websocket");
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const http = require('http');
const Sentry = require('@sentry/node');
const sentryInit = require('./src/config/sentryConfig');
const setRoutes = require('./src/routes/BaseRoutes');
const dailySchedule = require('./src/utils/schedule');
const { setupWebsocket } = require('./websocket');

const app = express();
sentryInit();
const server = http.Server(app);

app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb" }));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb' }));
setupWebsocket(server);

const databaseConnect = require("./src/config/database");
const databaseConnect = require('./src/config/database');

app.use(cors());
app.use(bodyParser.json());
Expand All @@ -24,4 +26,6 @@ databaseConnect();
dailySchedule();
setRoutes(app);

app.use(Sentry.Handlers.errorHandler());

server.listen(8000);
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"dev": "node server.js"
},
"dependencies": {
"@sentry/node": "5.18.0",
"bcrypt": "^4.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
Expand All @@ -19,7 +20,8 @@
"express": "^4.17.1",
"faker": "^4.1.0",
"firebase-admin": "^8.10.0",
"lodash": "^4.17.15",
"lodash": "^4.17.19",
"mongodb": "^3.5.9",
"mongoose": "^5.9.6",
"node-schedule": "^1.3.2",
"socket.io": "^2.3.0",
Expand Down
15 changes: 12 additions & 3 deletions src/config/authFirebase.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
const admin = require('firebase-admin');
const firebaseConfigDev = require('./firebaseConfig-dev');
const firebaseConfigProd = require('./firebaseConfig');

const admin = require("firebase-admin");
let firebaseConfig;
const enviroment = process.env.NODE_ENV;
if (enviroment === 'production') {
firebaseConfig = firebaseConfigProd;
} else {
firebaseConfig = firebaseConfigDev;
}

const { config, databaseURL } = require("./firebaseConfig");
const { databaseURL, config } = firebaseConfig;

admin.initializeApp({
credential: admin.credential.cert(config),
databaseURL: databaseURL
databaseURL,
});

module.exports = admin;
31 changes: 17 additions & 14 deletions src/config/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,25 @@ const databaseURL = process.env.DATABASE_URL || 'mongodb://mongo:27017/miaAjudaD
const envType = process.env.NODE_ENV || 'development';

const databaseConnect = async () => {
try {
await mongoose.connect(databaseURL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Banco de dados conectado!'))
.catch((error) => console.log('Não foi possível se conectar ao banco de dados!'));
try {
await mongoose.connect(databaseURL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Banco de dados conectado!'))
.catch((err) => {
console.log('Não foi possível se conectar ao banco de dados!');
console.log(err);
});

await CategorySeed();
// só popula usuários e ajudas falsos em desenvolvimento
if (envType === 'development') {
await UserSeed();
await HelpSeed();
await NotificationSeed();
}
} catch (error) {
console.log('Não foi possível inicicializar corretamente a base de dados!');
console.log(error);
await CategorySeed();
// só popula usuários e ajudas falsos em desenvolvimento
if (envType === 'development') {
await UserSeed();
await HelpSeed();
await NotificationSeed();
}
} catch (err) {
console.log('Não foi possível inicicializar corretamente a base de dados!');
console.log(err);
}
};

module.exports = databaseConnect;
14 changes: 14 additions & 0 deletions src/config/sentryConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const Sentry = require('@sentry/node');

const sentryInit = async () => {
const sentryDSN = process.env.SENTRY_DSN || null;
if (sentryDSN === null) {
console.log('Sentry não configurado. Os logs de erros não serão salvos na núvem.');
} else {
Sentry.init({
dsn: sentryDSN,
});
}
};

module.exports = sentryInit;
52 changes: 28 additions & 24 deletions src/controllers/CategoryController.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
const CategoryService = require('../services/CategoryService');
const saveError = require('../utils/ErrorHistory');

class CategoryController {
constructor() {
this.CategoryService = new CategoryService();
}
constructor() {
this.CategoryService = new CategoryService();
}

async getCategoryById(req, res, next) {
const { id } = req.params;

async getCategoryById(req, res, next) {
const { id } = req.params;
try {
const result = await this.CategoryService.getCategoryByid(id);
res.status(200).json(result);
next();
} catch (err) {
res.status(400).json({ error: err });
next();
}
try {
const result = await this.CategoryService.getCategoryByid(id);
res.status(200).json(result);
next();
} catch (err) {
saveError(err);
res.status(400).json({ error: err.message });
next();
}
}

async getCategoryList(req, res, next) {
const id = req.query.id || null;

async getCategoryList(req, res, next) {
const id = req.query.id || null;
try {
let result;
result = await this.CategoryService.getCategoryList(id);
res.status(200).json(result);
next();
} catch (err) {
res.status(400).json({ error: err });
next();
}
try {
const result = await this.CategoryService.getCategoryList(id);
res.status(200).json(result);
next();
} catch (err) {
saveError(err);
res.status(400).json({ error: err.message });
next();
}
}
}

module.exports = CategoryController;
Loading

0 comments on commit 6fdb054

Please sign in to comment.