sswellington / omniStack11

Be The Hero se destina a promover campanhas tendo a finalidade em auxiliar custos das ONGs

Home Page:https://www.figma.com/file/2C2yvw7jsCOGmaNUDftX9n/Be-The-Hero---OmniStack-11?node-id=37%3A394

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Semana OmniStack 11:

Configuração de Ambiente Back-end Front-end Mobile TDD Git Tags
Estrutura de diretórios Node.js React.js React Native Joi Feat
Visual Studio Code Rota e Recursos React Icons Expo Celebrate Docs
Node.js Banco de dados React Router Dom React Navigation Jest Style
Nodemon CORS Cliente HTTP Cliente HTTP Cross-Env Refactor
Insomnia.rest Intl Supertest Test
Chore

alt text


Configuração de Ambiente:

Estrutura de diretórios

./backend

  • ./scr
    • ./controllers
    • ./utils
    • ./database
      • ./migration
  • ./tests
    • ./integration
    • ./unit

./frontend

  • ./public
  • ./scr
    • ./assets
    • ./pages
      • ./Logon
      • ./NewIncident
      • ./Profile
      • ./Register
    • ./services

./mobile

  • ./assets
  • ./scr
    • ./assets
    • ./pages
      • ./Detail
      • ./Incidents
    • ./services

Visual Studio Code: Plugins (Ctrl+P)

* ext install spywhere.guides
* ext install eamodio.gitlens
* ext install christian-kohler.path-intellisense
* ext install vscode-icons-team.vscode-icons	

Node.js

Instalar o node.js

  • npm: instala um pacote
  • npx: executa um pacote
 node -v #mostra a versão do node
 npm -v  #mostra a versão do npm

Nodemon

  • Atualiza automaticamente o servido do Node.js
npm install nodemon # em todo o programa
npm install nodemon -D # apenas na dependência de desenvolvimento
npm start # ativa e atualiza automaticamente o localhost:3333 

Git

Mensagens para Commit

  • feat: um novo recurso
  • fix: uma correção de bug
  • docs: alterações na documentação
  • style: formatação, falta de dois pontos, etc; nenhuma mudança de código
  • refactor: refatoração do código de produção
  • test: adicionando testes, teste de refatoração; nenhuma mudança de código de produção
  • chore: atualizar tarefas de compilação, configurações do gerenciador de pacotes, etc; nenhuma mudança de código de produção

Deploy

Hospedagem da aplicação

Backend - Nodejs

Fluxo pequeno

Fluxo médio

Fluxo grande

  • AWS
  • Google Cloud Platform
  • MicrosofEasy Microsoft Azure

Frontend - React

Fluxo pequeno

  • Netlify

Padrão de código

  • ESLint
  • Prettier

Autentificação: JWT

Syled Components


Back-end

Node.js

Hello world

 mkdir backend
 cd backend
 npm init -y # incializando node.js
 npm install express # instalando micro-framework 'express' (configura rota e interpreta parâmetros)
 touch index.js 
  • request: guarda todos os dados que são fornecidos da requisição do usuário
  • response: responder todos os dados que são requisitados pelo usuário
const express = require('express'); 

const app = express();

app.get('/',(request, response) => {
	return response.send('Hello World');
});

app.listen(3333);
 node index.js # ativa o localhost:3333

Rota e Recursos

Métodos HTTP

  • GET: Buscar/Listar uma informação do back-end
  • POST: Cria uma informação do back-end
  • PUT: Altera uma informação do back-end
  • DELETE: Delete uma informação do back-end

Insomnia.rest : (Ferramenta para manipular os Métodos HTTP)

$ sudo snap install insomnia 
Login

Client Code

var data = JSON.stringify({
  "id": "aa1e8513"
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:3333/sessions");
xhr.setRequestHeader("authorization", "aa1e8513");
xhr.setRequestHeader("content-type", "application/json");

xhr.send(data);
POST /sessions HTTP/1.1
Authorization: aa1e8513
Content-Type: application/json
Host: localhost:3333
Content-Length: 22

{
	"id" : "aa1e8513"
}

Curl

curl --request POST \
  --url http://localhost:3333/sessions \
  --header 'authorization: aa1e8513' \
  --header 'content-type: application/json' \
  --data '{
	"id" : "aa1e8513"
}'
Profile

Client Code

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "http://localhost:3333/profile");
xhr.setRequestHeader("authorization", "aa1e8513");

xhr.send(data);
GET /profile HTTP/1.1
Authorization: aa1e8513
Host: localhost:3333

Curl

curl --request GET \
  --url http://localhost:3333/profile \
  --header 'authorization: aa1e8513'
Casos
  • List

Client Code

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "http://localhost:3333/incidents?page=1");
xhr.setRequestHeader("authorization", "aa1e8513");

xhr.send(data);
GET /incidents?page=1 HTTP/1.1
Authorization: aa1e8513
Host: localhost:3333

Curl

curl --request GET \
  --url 'http://localhost:3333/incidents?page=1' \
  --header 'authorization: aa1e8513'
  • Create

Client Code

var data = JSON.stringify({
  "title": "Casos 1",
  "description": "Detalhes dos casos",
  "value": 120
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:3333/incidents");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("authorization", "aa1e8513");

xhr.send(data);
POST /incidents HTTP/1.1
Content-Type: application/json
Authorization: aa1e8513
Host: localhost:3333
Content-Length: 89

{ 
	"title" 			: "Casos 1",  
	"description" : "Detalhes dos casos", 
	"value" 			: 120
}

Curl

curl --request POST \
  --url http://localhost:3333/incidents \
  --header 'authorization: aa1e8513' \
  --header 'content-type: application/json' \
  --data '{ 
	"title" 			: "Casos 1",  
	"description" : "Detalhes dos casos", 
	"value" 			: 120
}'
  • Delete

Client Code

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("DELETE", "http://localhost:3333/incidents/3");
xhr.setRequestHeader("authorization", "aa1e8513");

xhr.send(data);
DELETE /incidents/3 HTTP/1.1
Authorization: aa1e8513
Host: localhost:3333

Curl

curl --request DELETE \
  --url http://localhost:3333/incidents/3 \
  --header 'authorization: aa1e8513'
Ongs
  • List

Client Code

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "http://localhost:3333/ongs");

xhr.send(data);
GET /ongs HTTP/1.1
Host: localhost:3333

Curl

curl --request GET \
  --url http://localhost:3333/ongs
  • Create

Client Code

var data = JSON.stringify({
  "name": "APAD2",
  "email": "contato@apad.com.br",
  "whatsapp": "470000000",
  "city": "Rio do Sul",
  "uf": "SC"
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:3333/ongs");
xhr.setRequestHeader("content-type", "application/json");

xhr.send(data);
POST /ongs HTTP/1.1
Content-Type: application/json
Host: localhost:3333
Content-Length: 131

{
	"name" 		 : "APAD2",
	"email" 	 : "contato@apad.com.br",
	"whatsapp" : "470000000",
	"city" 		 : "Rio do Sul",
	"uf"			 : "SC"
}

Curl

curl --request POST \
  --url http://localhost:3333/ongs \
  --header 'content-type: application/json' \
  --data '{
	"name" 		 : "APAD2",
	"email" 	 : "contato@apad.com.br",
	"whatsapp" : "470000000",
	"city" 		 : "Rio do Sul",
	"uf"			 : "SC"
}'

Tipos de parâmetros

  • Query Params: parâmetros nomeados enviados na rota após "?". Exemplo: filtro, páginação;
  • Route Params: parâmetros utilizados para identificar recursos ;
  • Request Body: Corpo da requisição, utilizado para criar ou alterar recursos.
    • Converter json para javascript: app.use(express.json());.

Banco de dados

Modelo Conceitual: Entidades e Funcionalidades

  • ONG
    • Cadastrar
    • Login
    • Logout
    • Contato
  • CASOS (incident)
    • Cadastrar
    • Deletar
    • Listar
      • Especificos
      • Todos
  • Driver: SELECT * FROM users
  • Query Builder: table('users').select( * ).where()
  • Install
npm install knex 
npm install sqlite3
npx knex init # configura o acesso ao banco de dados para cada aplicação

Migrations

  • Configuração do database pelo knex
// knexfile.js
development: {
    client: 'sqlite3',
    connection: {
        filename: './src/database/db.sqlite'
    },
    migrations: {
        directory: './src/database/migrations'
    },
    useNullAsDefault: true
},
  • gera uma tabela apenas no knexfile create schema
npx knex migrate:make create_ongs 
  • configura a estrutura da tabela para o comando create table
// 20200325083011_create_ongs.js
exports.up = function(knex) {
  return knex.schema.createTable('ong', function (table) {
    table.string('id').primary();
    table.string('name').notNullable();
    table.string('email').notNullable();
    table.string('whatsapp').notNullable();
    table.string('city').notNullable();
    table.string('uf',2).notNullable();
  })
};

exports.down = function(knex) { return knex.schema.dropTable('ongs'); };
  • executa o comando create table e cria tabela no banco de dados
npx knex migrate:latest 
  • Desfaz o último comando do npx knex migrate:latest
npx knex migrate:rollback

Módulo de Segurança

Cross-Origin Resource Sharing (CORS)

Define quem possui autoridade de acessar a aplicação

npm install cors 

Exemplo de uso:

app.use(cors({
    origin: 'domínio_da_app.com'
}));

Frontend

React.js

Criar projeto

cd..
npx create-react-app frontend #cria um projet
cd frontend
npm start

Servidor

npm start #porta 3000
serve -s build #porta 5000

Icones para React

cd frontend
npm install react-icons

Router no React

cd frontend
npm install react-router-dom

Cliente HTTP

cd frontend
npm install axios

Conceitos

  • Limpeza de Componente
  • JavaScript XML (JSX)

Propriedades (props)

export default function App() {
  return (
    <Header title="Semana"></Header>
  );
}

export default function Header(props) {
    return (
        <header>
            <h1> {props.title} </h1>
        </header>
    );
}
childen
export default function App() {
return (
    <Header> Semana OmniStack </Header>
);
}

export default function Header(props) {
    return (
        <header>
            <h1> {props.childen} </h1>
        </header>
    );
}
  • Estado
  • Imutabilidade

Configuração

  • Página de login
  • Configuração de rotas
  • ONGs
    • Cadastro
    • Listagem
    • cadastrar casos
  • Conectar aplicação à API

Mobile

React Native

Emulador

  • Direto no celular: instalar o app expo no android
  • Emulador online: snack.expo.io

Expo

sudo npm install -g expo-cli
expo init mobile
# template: blank 
cd mobile
npm start
npm start --reset-cache
expo install expo-constants
expo install expo-mail-composer

Correção de erros 🔨

internal/fs/watchers.js:177
internal/fs/watchers.js:177
    throw error;

Solução

sudo echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
npm install @react-navigation/native

expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view

npm install @react-navigation/stack

Cliente HTTP

cd mobile
npm install axios

Intl

npm install intl

TDD

Biblioteca de validação

Integra Joi com Express

npm install celebrate
npm install jest -D

Cross-Env

npm install cross-env

knexfile.js

module.exports = {
  development: {
    client: 'sqlite3',
    connection: {
      filename: './src/database/db.sqlite'
    },
    migrations: {
      directory: './src/database/migrations'
    },
    useNullAsDefault: true
  },

  test: {
    client: 'sqlite3',
    connection: {
      filename: './src/database/test.sqlite'
    },
    migrations: {
      directory: './src/database/migrations'
    },
    useNullAsDefault: true
  },

  staging: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  },

  production: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }
};

package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon src/server.js",
    "test": "cross-env NODE_ENV=test jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "celebrate": "^12.0.1",
    "cors": "^2.8.5",
    "cross-env": "^7.0.2",
    "express": "^4.17.1",
    "knex": "^0.20.13",
    "sqlite3": "^4.1.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.2",
    "jest": "^25.2.3",
    "supertest": "^4.0.2"
  }
}

npm install supertest -D

About

Be The Hero se destina a promover campanhas tendo a finalidade em auxiliar custos das ONGs

https://www.figma.com/file/2C2yvw7jsCOGmaNUDftX9n/Be-The-Hero---OmniStack-11?node-id=37%3A394


Languages

Language:JavaScript 85.7%Language:CSS 13.2%Language:HTML 1.0%