Skip to content

Commit

Permalink
Merge pull request #17 from pabrrs/dev
Browse files Browse the repository at this point in the history
Sugestão de boilerplate
  • Loading branch information
pabrrs authored May 29, 2020
2 parents da76517 + bdd4de8 commit cba80a1
Show file tree
Hide file tree
Showing 40 changed files with 5,589 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .docker/firebase.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FROM openjdk:alpine

ENV FIRESTORE_VERSION 1.4.0
ADD https://storage.googleapis.com/firebase-preview-drop/emulator/cloud-firestore-emulator-v$FIRESTORE_VERSION.jar ./cloud-firestore-emulator.jar

EXPOSE 5555

CMD ["java", "-jar", "./cloud-firestore-emulator.jar", "--host=0.0.0.0", "--port=5555"]
8 changes: 8 additions & 0 deletions .docker/node-dev.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FROM node:12.16.3

WORKDIR /var/app
COPY package.json .
RUN npm install
COPY . .

CMD ["npm", "start"]
13 changes: 13 additions & 0 deletions .docker/node-prod.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
FROM node:12.16.3-alpine

RUN apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /var/app

COPY package.json .
RUN npm install --only=production
COPY . .

CMD ["npm", "start"]
14 changes: 14 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Arquivos git
.git/
.github/
.gitignore

# Arquivos Docker
*.Dockerfile
docker-compose.yml

# Arquivos do projeto
node_modules/
.nyc_output/
README.md
CONTRIBUTING.md
4 changes: 4 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/.*/**
/coverage/**
/node_modules/**
/tmp/**
39 changes: 39 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"env": {
"commonjs": true,
"node": true
},
"extends": [
"airbnb",
"plugin:security/recommended",
"plugin:you-dont-need-lodash-underscore/compatible",
"prettier"
],
"plugins": ["prettier", "security", "no-unsafe-regex"],
"rules": {
"prettier/prettier": ["error"],
"no-unsafe-regex/no-unsafe-regex": "error",
"func-names": ["warn", "always", { "generators": "never" }],
"no-underscore-dangle": "off",
"camelcase": [
"error",
{
"properties": "never",
"ignoreDestructuring": true
}
],
"no-restricted-syntax": [
"error",
{
"selector": "LabeledStatement",
"message": "Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand."
},
{
"selector": "WithStatement",
"message": "`with` is disallowed in strict mode because it makes code impossible to predict and optimize."
}
],
"no-continue": "off",
"no-await-in-loop": "off"
}
}
6 changes: 6 additions & 0 deletions .mocharc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require:
- chai/register-expect
- test/setup.js
recursive: true
timeout: 6000
exit: true
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v12.16.3
64 changes: 64 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# next.js build output
.next

# IDE
.vscode
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"tabWidth": 2,
"semi": false,
"printWidth": 120
}
4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ Para contribuir com o projeto é necessário identificar issues que ainda estão
7- Adicione um Título e preencha o modelo na descrição do Pull Request para submetê-lo corretamente

8- Clique em **Create Pull Request**

## Orientações

Para mais informações sobre a estrutura do código de backend, clique [aqui](https://github.com/idvogados/backend/blob/dev/docs/orientacoes.md)
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
all:
make up
build:
docker-compose --build
up:
docker-compose up --detach --force-recreate --renew-anon-volumes --remove-orphans
22 changes: 22 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const express = require('express')
const healthRoutes = require('./src/routes/health-route')
const errorsMiddleware = require('./src/middlewares/errors-middleware')

const app = express()

// Middlewares
app.use(express.json())

// Rotas
app.use(healthRoutes)

/**
* Captura de erros.
* Deve ser feito depois da definição das rotas,
* para garantir que todo handler de uma rota que
* lance um erro, tenha esse erro capturado pelo
* middleware.
*/
app.use(errorsMiddleware)

module.exports = app
9 changes: 9 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env node

const app = require('../app')
const apiConfig = require('../src/config/api-config')
const logger = require('../src/client/logger-client')

app.listen(apiConfig.port, () => {
logger.info({ msg: `Listening on port ${apiConfig.port}` })
})
10 changes: 10 additions & 0 deletions docker-compose.test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: '3.6'

services:
idvogados_firebase:
container_name: idvogados_firebase
build:
context: ./
dockerfile: ./.docker/firebase.Dockerfile
ports:
- 5555:5555
23 changes: 23 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
version: '3.6'

services:
idvogados_api:
container_name: idvogados_api
build:
context: ./
dockerfile: ./.docker/node-dev.Dockerfile
environment:
NODE_ENV: development
API_PORT: 3001
ports:
- 3001:3001
depends_on:
- idvogados_firebase

idvogados_firebase:
container_name: idvogados_firebase
build:
context: ./
dockerfile: ./.docker/firebase.Dockerfile
ports:
- 5555:5555
89 changes: 89 additions & 0 deletions docs/configuracoes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Configurações Idvogados

Nesse documento você irá encontrar todas as configurações do projeto de backend.
Além disso, você pode encontrar um guia na sessão [como rodar](#como-rodar), explicando as diferentes formas para inicializar o projeto.

## Como rodar

O projeto pode ser inicializado de várias formas:

### Rodando com Node.js

Instale o [Node.js](https://nodejs.org/en/download/) na sua versão mais recente (LTS), então execute:

```sh
npm start
```

Você irá ver uma mensagem semelhante a:

```sh
> {"level":"info" ... "msg":"Listening on port 3000"}
```

Então acesse [http://localhost:3000](http://localhost:3000)

### Rodando com nvm (Node Version Manager)

Instale o [nvm](https://github.com/nvm-sh/nvm), então execute:

```sh
nvm install
nvm use
```

Você irá ver uma mensagem semelhante a:

```sh
Now using node v12.16.3 (npm v6.14.4)
```

Execute o comando `npm start` para subir o projeto e acesse [http://localhost:3000](http://localhost:3000)

### Rodando com Docker

Instale o [Docker](https://docs.docker.com/get-docker/) e [docker-compose](https://docs.docker.com/compose/gettingstarted/) na suas versões mais recentes, então rode os seguintes comandos:

```sh
docker-compose up --build
```

Você irá ver a seguinte mensagem:

```sh
> idvogados_firebase | Dev App Server is now running.
> idvogados_api | {"level":"info" ... "msg":"Listening on port 3000"}
```

### Rodar com Make

Para inicializar o projeto com o comando `make`, utilize os seguintes comandos:

```sh
make build
make up
```

## Variáveis de ambiente

### Configurações do Node.js

- `NODE_ENV`: Determina o ambiente onde a API será executada; Possíveis valores: `production|test|development`

**Obs:** Ao usar `NODE_ENV=test` as demais variáveis de ambiente devem ser prefixadas com `TEST_*`

### Configurações da API

- `API_PORT`: Define a porta onde a API será inicializada. Padrão: `3000`.

### Configurações de Log

- `LOG_LEVEL`: Define nível de log usado pela API, determinando a quantidade de log que será gerada pela aplicação. Os níveis suportados são: `fatal|error|warn|info|debug|trace|silent`. Padrão: `debug`.

### Configurações do Firebase

As seguintes variáveis de ambiente são utilizadas para configurar a conexão com o Firebase. A referência completa para cada variável pode ser encontrada na documentação [Firebase#initializeApp](https://firebase.google.com/docs/reference/node/firebase?hl=pt-br#initializeapp)

- `FIREBASE_API_KEY`: Api Key para conexão com o Firebase Cloud, encontrada no painel de configuração do Firebase.
- `FIREBASE_PROJECT_ID`: ID do projeto no Firebase Cloud, encontrada no painel de configuração do Firebase.
- `FIREBASE_FIRESTORE_HOST`: Host do Firestore para conexão local. Padrão: `localhost:5555`
Loading

0 comments on commit cba80a1

Please sign in to comment.