./scr./controllers./utils./database./migration
./tests./integration./unit
./public./scr./assets./pages./Logon./NewIncident./Profile./Register
./services
./assets./scr./assets./pages./Detail./Incidents
./services
* ext install spywhere.guides
* ext install eamodio.gitlens
* ext install christian-kohler.path-intellisense
* ext install vscode-icons-team.vscode-icons
npm: instala um pacotenpx: executa um pacote
node -v #mostra a versão do node
npm -v #mostra a versão do npm- Atualiza automaticamente o servido do
Node.js
npm install nodemon # em todo o programanpm install nodemon -D # apenas na dependência de desenvolvimentonpm start # ativa e atualiza automaticamente o localhost:3333 feat: um novo recursofix: uma correção de bugdocs: alterações na documentaçãostyle: formatação, falta de dois pontos, etc; nenhuma mudança de códigorefactor: refatoração do código de produçãotest: adicionando testes, teste de refatoração; nenhuma mudança de código de produçãochore: atualizar tarefas de compilação, configurações do gerenciador de pacotes, etc; nenhuma mudança de código de produção
Hospedagem da aplicação
- AWS
- Google Cloud Platform
- MicrosofEasy Microsoft Azure
- Netlify
- ESLint
- Prettier
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árioresponse: 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:3333GET: Buscar/Listar uma informação do back-endPOST: Cria uma informação do back-endPUT: Altera uma informação do back-endDELETE: Delete uma informação do back-end
Insomnia.rest : (Ferramenta para manipular os Métodos HTTP)
$ sudo snap install insomnia 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"
}'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:3333Curl
curl --request GET \
--url http://localhost:3333/profile \
--header 'authorization: aa1e8513'
- 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:3333Curl
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:3333Curl
curl --request DELETE \
--url http://localhost:3333/incidents/3 \
--header 'authorization: aa1e8513'
- 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:3333Curl
curl --request GET \
--url http://localhost:3333/ongs
- Create
Client Code
var data = JSON.stringify({
"name": "APAD2",
"email": "[email protected]",
"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" : "[email protected]",
"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" : "[email protected]",
"whatsapp" : "470000000",
"city" : "Rio do Sul",
"uf" : "SC"
}'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());.
- Converter json para javascript:
- 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 sqlite3npx knex init # configura o acesso ao banco de dados para cada aplicação- 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 tablee cria tabela no banco de dados
npx knex migrate:latest - Desfaz o último comando do
npx knex migrate:latest
npx knex migrate:rollbackDefine quem possui autoridade de acessar a aplicação
npm install cors Exemplo de uso:
app.use(cors({
origin: 'domínio_da_app.com'
}));cd..
npx create-react-app frontend #cria um projet
cd frontend
npm startnpm start #porta 3000
serve -s build #porta 5000cd frontend
npm install react-iconscd frontend
npm install react-router-domcd frontend
npm install axios- Limpeza de Componente
- JavaScript XML (JSX)
export default function App() {
return (
<Header title="Semana"></Header>
);
}
export default function Header(props) {
return (
<header>
<h1> {props.title} </h1>
</header>
);
}export default function App() {
return (
<Header> Semana OmniStack </Header>
);
}
export default function Header(props) {
return (
<header>
<h1> {props.childen} </h1>
</header>
);
}- Estado
- Imutabilidade
- Página de login
- Configuração de rotas
- ONGs
- Cadastro
- Listagem
- cadastrar casos
- Conectar aplicação à API
- Direto no celular: instalar o app
expono android - Emulador online: snack.expo.io
sudo npm install -g expo-cliexpo init mobile
# template: blank
cd mobile
npm start
npm start --reset-cacheexpo install expo-constantsexpo install expo-mail-composerinternal/fs/watchers.js:177
throw error;sudo echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -pnpm 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/stackcd mobile
npm install axiosnpm install intlBiblioteca de validação
Integra Joi com Express
npm install celebratenpm install jest -Dnpm install cross-envknexfile.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
