Skip to content

Commit

Permalink
Merge pull request #8 from fga-eps-mds/feature/#143-CI_CD
Browse files Browse the repository at this point in the history
Feature/#143 ci cd
  • Loading branch information
HenriqueAmorim20 authored Oct 24, 2023
2 parents c6cd3f9 + f91ee3b commit a28edaa
Show file tree
Hide file tree
Showing 15 changed files with 409 additions and 9,555 deletions.
13 changes: 9 additions & 4 deletions .docker/entrypoint.prod.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
#!/bin/bash
# TODO
npm install
npm run start:dev
#!/bin/sh

echo "---------------Run migrations---------------"

node /app/migrations.js

echo "---------------Run migrations - END---------"

node /app/main.js
11 changes: 9 additions & 2 deletions .docker/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
#!/bin/bash

cd /home/node/app
source .env.development

npm install --legacy-peer-deps

rm -rf dist

echo "---------------Run migrations---------------"

npm run typeorm:run

echo "---------------Run migrations - END---------"
npm run start:dev

npm run start:debug
10 changes: 4 additions & 6 deletions .docker/entrypoint.test.sh
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
#!/bin/bash

echo ".................................."
echo "TEST CONTAINER:"

cd home/node/app
echo "TEST:" $TEST

npm install --legacy-peer-deps
npm run build
npm run lint
npm run typeorm:run


if ! [ -z $TEST ] && [ $TEST == 'unit' ]; then
echo "Running unit tests"
npm run test:cov
Expand All @@ -20,7 +18,7 @@ elif ! [ -z $TEST ] && [ $TEST == 'lint' ]; then
echo "Running lint"
npm run lint
npm run format
else
echo "Running test"
elif ! [ -z $TEST ] && [ $TEST == 'dev' ]; then
echo "Running dev"
npm run start:dev
fi
2 changes: 1 addition & 1 deletion .docker/postgres/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ ENV LANG pt_BR.utf8
ENV LC_ALL pt_BR.utf8
ENV LANGUAGE pt_BR.utf8

EXPOSE 5432
EXPOSE 5001
3 changes: 2 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,14 @@ jobs:
TEST=e2e docker-compose -f docker-compose.test.yml up -V --force-recreate --build --abort-on-container-exit --exit-code-from gerocuidado-usuario-api-test
env:
TEST: e2e

sonarqube:
name: sonarqube
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
fetch-depth: 0
- name: Install dependencies
run: yarn
- name: Test and coverage
Expand Down
47 changes: 47 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Deploy

on:
push:
branches: ['main']
tags: ['v*.*.*']

env:
TARGET_DIR: '~/${{ github.event.repository.name }}'

jobs:
docker-hub:
name: Docker Hub Image Push
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3

- name: Sending Image to Docker Hub
uses: mr-smithers-excellent/docker-build-push@v5
with:
image: gerocuidadodev/gerocuidado-usuario-api
registry: docker.io
directory: ./
dockerfile: ./Dockerfile.prod
tags: latest
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}

deploy-ec2:
name: Deploy EC2
needs: docker-hub
runs-on: ubuntu-latest
steps:
- name: Checkout the files
uses: actions/checkout@v2

- name: Executing remote ssh commands using ssh key
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.EC2_HOST_DNS }}
username: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_SSH_KEY }}
script: |
cd ${{env.TARGET_DIR}}
sudo git pull
sudo docker compose -f docker-compose.prod.yml up --force-recreate --build --pull --remove-orphans -d
3 changes: 2 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
{
"type": "node",
"request": "attach",
"protocol": "inspector",
"restart": true,
"name": "gerocuidado-usuario-api",
"name": "API",
"port": 7001,
"address": "0.0.0.0",
"localRoot": "${workspaceFolder}/",
Expand Down
15 changes: 3 additions & 12 deletions Dockerfile.prod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:18.13.0 AS BUILD_IMAGE
FROM node:18.17.0-alpine AS BUILD_IMAGE

RUN apk update && apk add curl bash make && rm -rf /var/cache/apk/*

Expand All @@ -15,7 +15,7 @@ COPY . .
RUN npm run build


FROM node:18.13.0 AS BUILD_NODE_MODULES
FROM node:18.17.0-alpine AS BUILD_NODE_MODULES

RUN apk update && apk add curl bash make && rm -rf /var/cache/apk/*

Expand All @@ -26,19 +26,10 @@ COPY package*.json ./
RUN npm ci --legacy-peer-deps --omit=dev


FROM node:18.13.0
FROM node:18.17.0-alpine

ENV NODE_ENV=production

ARG TZ='America/Sao_Paulo'

ENV TZ ${TZ}

RUN apk upgrade --update
RUN apk add --no-cache tzdata
RUN cp /usr/share/zoneinfo/${TZ} /etc/localtime
RUN echo "${TZ}" > /etc/timezone

WORKDIR /app

COPY --chown=node:node --from=BUILD_IMAGE /home/node/app/dist /app
Expand Down
107 changes: 51 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,86 +1,81 @@
# GEROcuidado-APIUsuario
# gerocuidado-usuario-api

## CONFIGURAÇÃO
## Configuração

Definir valores iguais para os arquivos .env e docker-compose.
Definir valores iguais para os arquivos .env e docker-compose

Arquivo .env:
Arquivo .env.development e .env.test:

#POSTGRES
DB_TYPE='postgres'
DB_HOST='localhost'
DB_USERNAME='postgres'
DB_PASS='postgres'
DB_DATABASE='gerocuidado-usuario-db'
DB_PORT=5001
DB_TYPE=
DB_HOST=
DB_USERNAME=
DB_PASS=
DB_DATABASE=
DB_PORT=
JWT_TOKEN_SECRET=
JWT_TOKEN_EXPIRES_IN=
HASH_SALT=

Arquivo .docker-compose, na seção **_environment_**:

...
environment:
- POSTGRES_DB=gerocuidado-usuario-db
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=
- POSTGRES_USER=
- POSTGRES_PASSWORD=
...

Da mesma forma, alterar os valores das portas terminadas em **_xx_** (i.e 30xx para 3001) para a porta desejada nos arquivos de compose, bem como no arquivo launch.json da pasta .vscode.
Da mesma forma, alterar os valores das portas terminadas em **_x_** (i.e 300x para 3001) para a porta desejada nos arquivos de compose, bem como no arquivo launch.json da pasta .vscode.

## AMBIENTES
## Execução

### DEV
Para subir a aplicação, basta rodar o comando:

```bash
docker-compose up
```

#### INSTALAR DEPENDÊNCIAS E CRIAR NOVAS FUNCIONALIDADES

```bash
docker-compose exec gerocuidado-usuario-api bash
nest g resource users
```
```bash
docker compose up
```

### TEST
## Testes

- GERAL
Para testar a aplicação, suba o container de testes:

```bash
docker-compose -f docker-compose.test.yml up
TEST=dev docker compose -f docker-compose.test.yml up
```

após em um novo terminal

E rode os comandos para os testes unitários e E2E respectivamente (:cov gera o arquivo de coverage na raiz do projeto):
```bash
docker-compose -f docker-compose.test.yml exec gerocuidado-usuario-api-test bash
cd /home/node/app
npm run test
npm run test:cov
npm run test:e2e
npm run test:e2e:cov
npm run test:cov
npm run test:e2e:cov
```

- UNIT
## Migrations

Para apenas rodar os testes unitários e sair do container rode o comando abaixo:
Sempre que houver qualquer alteração em alguma entidade na aplicação (adicionar uma entidade, remover ou edita-la), deve ser gerada uma migration para sincronizar o banco de dados.

```bash
TEST=unit docker-compose -f docker-compose.test.yml up --abort-on-container-exit --exit-code-from gerocuidado-usuario-api-test
```
1. Entrar no container da api:

- E2E
Para apenas rodar os testes unitários e sair do container rode o comando abaixo:
```bash
docker exec -it gerocuidado-usuario-api bash
```

```bash
TEST=e2e docker-compose -f docker-compose.test.yml up --abort-on-container-exit --exit-code-from gerocuidado-usuario-api-test
```
2. Rodar o comando de criar uma migration (tente dar um nome descritivo, ex.: CreateTableUsuario)

# ENVIRONMENTS VARIABLES
```bash
npm run typeorm:migrate src/migration/NOME_DA_MIGRATION
```

| ENV | Descrição | Valor Padrão |
| ----------- | ---------------------- | ---------------------- |
| DB_TYPE | tipo do banco | postgres |
| DB_HOST | host do PostgreSQL | localhost |
| DB_USERNAME | usuário do PostgreSQL | postgres |
| DB_PASS | senha do PostgreSQL | postgres |
| DB_DATABASE | database do PostgreSQL | gerocuidado-usuario-db |
| DB_PORT | porta do PostgreSQL | 5001 |
# Dicionário variáveis de ambiente

| ENV | Descrição | Valor Padrão |
| -------------------- | ------------------------- | ---------------------- |
| DB_TYPE | tipo do banco | postgres |
| DB_HOST | host do PostgreSQL | localhost |
| DB_USERNAME | usuário do PostgreSQL | postgres |
| DB_PASS | senha do PostgreSQL | postgres |
| DB_DATABASE | database do PostgreSQL | gerocuidado-usuario-db |
| DB_PORT | porta do PostgreSQL | 5001 |
| JWT_TOKEN_SECRET | secret do JWT | |
| JWT_TOKEN_EXPIRES_IN | tempo de expiração do JWT | 12h |
| HASH_SALT | saltRounds da senha | 10 |
41 changes: 41 additions & 0 deletions docker-compose.prod.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
version: '3.7'
services:
gerocuidado-usuario-api-prod:
image: gerocuidadodev/gerocuidado-usuario-api:latest
container_name: gerocuidado-usuario-api-prod
environment:
- DB_HOST=gerocuidado-usuario-db
- DB_USERNAME=postgres
- DB_PASS=postgres
- DB_DATABASE=gerocuidado-usuario-db
- DB_PORT=5001
- JWT_TOKEN_SECRET=f57d8cc37a35a8051aa97b5ec8506a2ac479e81f82aed9de975a0cb90b903044
- JWT_TOKEN_EXPIRES_IN=12h
- HASH_SALT=10
ports:
- '3001:3001'
depends_on:
- gerocuidado-usuario-db
networks:
- gerocuidado-usuario-net

gerocuidado-usuario-db:
build:
context: ./.docker/postgres
dockerfile: Dockerfile
command: postgres -c 'config_file=/etc/postgresql/postgresql.conf'
container_name: gerocuidado-usuario-db
volumes:
- './.docker/postgres/config/postgresql.conf:/etc/postgresql/postgresql.conf'
environment:
- POSTGRES_DB=gerocuidado-usuario-db
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- '5001:5001'
networks:
- gerocuidado-usuario-net

networks:
gerocuidado-usuario-net:
driver: bridge
5 changes: 3 additions & 2 deletions docker-compose.test.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
version: '3.7'
services:
gerocuidado-usuario-api-test:
image: node:18.13.0
image: gerocuidadodev/node:18.17.0-alpine-dev
container_name: gerocuidado-usuario-api-test
volumes:
- '.:/home/node/app'
entrypoint: bash /home/node/app/.docker/entrypoint.test.sh
entrypoint: dockerize -wait tcp://gerocuidado-usuario-db-test:5001 -timeout 40s ./.docker/entrypoint.test.sh
environment:
- NODE_ENV=test
- TEST=$TEST
Expand All @@ -23,6 +23,7 @@ services:
context: ./.docker/postgres
dockerfile: Dockerfile
command: postgres -c 'config_file=/etc/postgresql/postgresql.conf'
container_name: gerocuidado-usuario-db-test
volumes:
- './.docker/postgres/config/postgresql.conf:/etc/postgresql/postgresql.conf'
environment:
Expand Down
Loading

0 comments on commit a28edaa

Please sign in to comment.