diff --git a/semana17/aula51/package-lock.json b/semana17/aula51/package-lock.json index 76f1c4a..b98da72 100644 --- a/semana17/aula51/package-lock.json +++ b/semana17/aula51/package-lock.json @@ -82,6 +82,15 @@ "integrity": "sha512-+0GPv/hIFNoy8r5MFf7vRpBjnqNYNrlHdetoy23E7TYc7JB2ctwyi3GMKpviozaHQ/Sy2kBNUTvG9ywN66zV1g==", "dev": true }, + "@types/nodemailer": { + "version": "6.4.4", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.4.tgz", + "integrity": "sha512-Ksw4t7iliXeYGvIQcSIgWQ5BLuC/mljIEbjf615svhZL10PE9t+ei8O9gDaD3FPCasUJn9KTLwz2JFJyiiyuqw==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, "@types/qs": { "version": "6.9.7", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz", @@ -699,6 +708,11 @@ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" }, + "nodemailer": { + "version": "6.6.3", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.6.3.tgz", + "integrity": "sha512-faZFufgTMrphYoDjvyVpbpJcYzwyFnbAMmQtj1lVBYAUSm3SOy2fIdd9+Mr4UxPosBa0JRw9bJoIwQn+nswiew==" + }, "normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", diff --git a/semana17/aula51/package.json b/semana17/aula51/package.json index 3d8f940..1c8faac 100644 --- a/semana17/aula51/package.json +++ b/semana17/aula51/package.json @@ -6,7 +6,10 @@ "scripts": { "start": "tsc && node ./build/index.js", "dev": "tsnd ./src/index.ts", - "test": "echo \"Error: no test specified\" && exit 1" + "test": "echo \"Error: no test specified\" && exit 1", + "addressInfo": "tsnd ./src/services/getAddressInfo.ts", + "migrations": "tsnd ./src/data/migrations.ts", + "mail": "tsnd ./src/endpoints/sendEmail.ts" }, "keywords": [], "author": "", @@ -17,7 +20,8 @@ "dotenv": "^10.0.0", "express": "^4.17.1", "knex": "^0.95.8", - "mysql": "^2.18.1" + "mysql": "^2.18.1", + "nodemailer": "^6.6.3" }, "devDependencies": { "@types/axios": "^0.14.0", @@ -25,6 +29,7 @@ "@types/express": "^4.17.13", "@types/knex": "^0.16.1", "@types/node": "^16.4.5", + "@types/nodemailer": "^6.4.4", "ts-node-dev": "^1.1.8", "typescript": "^4.3.5" } diff --git a/semana17/aula51/request.rest b/semana17/aula51/request.rest index 293cd86..ab0381d 100644 --- a/semana17/aula51/request.rest +++ b/semana17/aula51/request.rest @@ -1 +1,12 @@ -GET http://localhost:3003/ \ No newline at end of file +GET http://localhost:3003/address + +### + +POST http://localhost:3003/address +Content-Type: application/json + +{ + "nome": "Bolsa de cocô", + "cep": "70150-903", + "numero": 1 +} diff --git a/semana17/aula51/src/app.ts b/semana17/aula51/src/app.ts index 51d7ed7..95c2834 100644 --- a/semana17/aula51/src/app.ts +++ b/semana17/aula51/src/app.ts @@ -1,18 +1,18 @@ -import express from "express"; -import cors from "cors"; -import {AddressInfo} from "net"; +import express from "express" +import cors from "cors" +import {AddressInfo} from "net" const app = express(); -app.use(express.json()); -app.use(cors()); +app.use(express.json()) +app.use(cors()) -const server = app.listen(process.env.PORT || 3003, () => { - if(server) { - const adress= server.address() as AddressInfo; - console.log(`Server running on http://localhost:${adress.port}`); - } else { - console.error(`Servidor não iniciado`) - } +const server = app.listen(process.env.PORT || 3003, ():void => { + if(server){ + const address = server.address() as AddressInfo; + console.log(`Server running on http://localhost:${address.port}`) + return; + } + console.error('Servidor não inciado!') }) export default app \ No newline at end of file diff --git a/semana17/aula51/src/connection.ts b/semana17/aula51/src/data/connection.ts similarity index 71% rename from semana17/aula51/src/connection.ts rename to semana17/aula51/src/data/connection.ts index 866d579..e2e6667 100644 --- a/semana17/aula51/src/connection.ts +++ b/semana17/aula51/src/data/connection.ts @@ -1,19 +1,18 @@ import knex from "knex" -import dotenv from "dotenv"; - +import dotenv from "dotenv" dotenv.config() const connection = knex ({ - client: "mysql", + client: 'mysql', connection: { host: process.env.DB_HOST, - port: 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_SCHEMA, - multiStatements: true + port: 3306, + multipleStatements: true } }) -export default connection; \ No newline at end of file +export default connection \ No newline at end of file diff --git a/semana17/aula51/src/data/migrations.ts b/semana17/aula51/src/data/migrations.ts new file mode 100644 index 0000000..edaf2c8 --- /dev/null +++ b/semana17/aula51/src/data/migrations.ts @@ -0,0 +1,38 @@ +import connection from "./connection"; +import users from './users.json' + +const printError = (error:any) => { console.log(error.sqlMessage || error.message )} + +const createTables = async():Promise => { + try { + const criaTabela = await connection.raw(` + CREATE TABLE IF NOT EXISTS aula51_users ( + id VARCHAR(255) PRIMARY KEY, + nome VARCHAR(255) NOT NULL, + cep VARCHAR(255) NOT NULL, + logradouro VARCHAR(255) NOT NULL, + numero INT NOT NULL, + complemento VARCHAR(255), + bairro VARCHAR(255) NOT NULL, + localidade VARCHAR(255) NOT NULL, + uf VARCHAR(255) NOT NULL + ) + `) + if(criaTabela){ + return console.log('Tabela criada!') + } + } catch (error) { + printError + } +} + +const insertEndereco = async () => await connection('aula51_users') +.insert(users) +.then(() => {console.log("Endereço adicionado!") }) +.catch(printError) + +const closeConnection = () => connection.destroy() + +createTables() +.then(insertEndereco) +.finally(closeConnection) \ No newline at end of file diff --git a/semana17/aula51/src/data/selectAllAdresses.ts b/semana17/aula51/src/data/selectAllAdresses.ts index 95599d5..23d6e6f 100644 --- a/semana17/aula51/src/data/selectAllAdresses.ts +++ b/semana17/aula51/src/data/selectAllAdresses.ts @@ -1,4 +1,4 @@ -import connection from "../connection" +import connection from "./connection" export default async function selectAllUsers(): Promise { const result = await connection.raw ( diff --git a/semana17/aula51/src/data/users.json b/semana17/aula51/src/data/users.json new file mode 100644 index 0000000..111a832 --- /dev/null +++ b/semana17/aula51/src/data/users.json @@ -0,0 +1,13 @@ +[ + { + "id": 1, + "nome": "AA", + "cep": "05424-150", + "logradouro": "Rua Pais Leme", + "numero": 25, + "complemento": "lado ímpar", + "bairro": "Pinheiros", + "localidade": "São Paulo", + "uf": "SP" + } +] diff --git a/semana17/aula51/src/endpoints/createUser.ts b/semana17/aula51/src/endpoints/createUser.ts new file mode 100644 index 0000000..5f11ea7 --- /dev/null +++ b/semana17/aula51/src/endpoints/createUser.ts @@ -0,0 +1,44 @@ +import { user } from "../types"; +import { Request, Response } from "express" +import { getAddressInfo } from "../services/getAddressInfo"; +import connection from "../data/connection"; +import transporter from "../services/mailTransporter"; + +export default async function createUser( + req: Request, + res: Response +): Promise { + try { + + const {nome, cep, numero, complemento} = req.body + + if (!nome || !cep || !numero) { + res.status(422).send({error: "nome, cep e número são obrigatórios"}) + } + + const id: string = Date.now().toString() + + const {logradouro, bairro, localidade, uf}: any = await getAddressInfo(cep) + + const newUser:user = {id, nome, cep, logradouro, numero, complemento, bairro, localidade, uf} + await connection('aula51_users').insert(newUser) + + + // const mailInfo = await transporter.sendMail({ + // from: `<${process.env.NODEMAILER_USER}>`, + // to: email + // }) + + res.status(201).send("Usuário criado!") + + + } catch (error) { + + if (res.status(200)) { + res.status(500).send({error: "Erro interno do servidor"}) + } else { + res.send({error: error.sqlMessage || error.message}) + } + + } +} \ No newline at end of file diff --git a/semana17/aula51/src/endpoints/getAllAdresses.ts b/semana17/aula51/src/endpoints/getAllAdresses.ts index 8763653..d744e38 100644 --- a/semana17/aula51/src/endpoints/getAllAdresses.ts +++ b/semana17/aula51/src/endpoints/getAllAdresses.ts @@ -2,10 +2,10 @@ import {Request, Response} from "express" import selectAllUsers from "../data/selectAllAdresses" -export const getAllAdresses = async (req:Request, res: Response): Promise => { +export const getAllAddresses = async (req:Request, res: Response): Promise => { try { - const allAdresses = await selectAllUsers() - res.status(200).send(allAdresses) + const allAddresses = await selectAllUsers() + res.status(200).send(allAddresses) } catch (error) { console.log(error) } diff --git a/semana17/aula51/src/endpoints/sendEmail.ts b/semana17/aula51/src/endpoints/sendEmail.ts new file mode 100644 index 0000000..a64978b --- /dev/null +++ b/semana17/aula51/src/endpoints/sendEmail.ts @@ -0,0 +1,25 @@ +import transporter from "../services/mailTransporter" + + +const sendEmail = async():Promise => { + try { + const mailInfo= await transporter.sendMail({ + from: `<${process.env.NODEMAILER_USER}>`, + to: "g6e8k2i3m1o7e5d9@labenualunos.slack.com", + subject:"Desafio aula 51", + text:` o objeto foi: sendMail({ + from: {process.env.NODEMAILER_USER}, + to: g6e8k2i3m1o7e5d9@labenualunos.slack.com, + subject:Desafio aula 51, + text:` + }) + + console.log(mailInfo) + } catch (error) { + console.log(error) + } + +} + +sendEmail() + diff --git a/semana17/aula51/src/index.ts b/semana17/aula51/src/index.ts index 03410a3..4e25c06 100644 --- a/semana17/aula51/src/index.ts +++ b/semana17/aula51/src/index.ts @@ -1,6 +1,7 @@ import app from "./app" -import { getAllAdresses } from "./endpoints/getAllAdresses" -// INSERIMOS DADOS NA TABELA COM O COMANDO INSERT INTO aula_51 (`id`, `zipcode`, `street`, `number`, `neighbourhood`, `city`, `state`) VALUES (1, '30330-010', 'rua dos bobos', 0, "Sao Pedro", "BH", "MG"); +import createUser from "./endpoints/createUser" +import { getAllAddresses } from "./endpoints/getAllAdresses" -app.get ('/address', getAllAdresses) \ No newline at end of file +app.get ('/address', getAllAddresses) +app.post('/address', createUser) \ No newline at end of file diff --git a/semana17/aula51/src/services/getAddressInfo.ts b/semana17/aula51/src/services/getAddressInfo.ts new file mode 100644 index 0000000..ae5ebc4 --- /dev/null +++ b/semana17/aula51/src/services/getAddressInfo.ts @@ -0,0 +1,39 @@ +import axios from "axios" +import { addressInfo } from "../types" + +export const getAddressInfo = async ( + zipcode: string +): Promise => { + try { + + const result = await axios.get(`https://viacep.com.br/ws/${zipcode}/json/`) + const {cep, logradouro, bairro, localidade, uf} = result.data + + const endereco ={ + cep, + logradouro, + bairro, + localidade, + uf + } + + return endereco + } catch (error) { + console.log(error.response ? error.response.data : error.message) + return null + } + +} +const address = async() => { + const cep = '70150-900' + const result = await getAddressInfo(cep) + return console.log(result) +} +address() + +// getAddressInfo('70150-900') +// .then(console.log) +// .catch(console.log) + + + diff --git a/semana17/aula51/src/services/getAdressInfo.ts b/semana17/aula51/src/services/getAdressInfo.ts deleted file mode 100644 index 6444887..0000000 --- a/semana17/aula51/src/services/getAdressInfo.ts +++ /dev/null @@ -1,24 +0,0 @@ -import axios from "axios" -import { addressInfo } from "../types" - -export const getAddressInfo = async( - zipcode: string -):Promise => { - try { - const result = await axios.get(`https://viacep.com.br/ws/${zipcode}/json/`) - - return { - zipcode: result.data.zipcode, - street: result.data.street, - number: result.data.number, - complement: result.data.complement, - neighbourhood: result.data.neighbourhood, - city: result.data.city, - state: result.data.state - } - } catch (error) { - console.log(error.response ? error.response.data : error.message); - return null - } - -} \ No newline at end of file diff --git a/semana17/aula51/src/services/mailTransporter.ts b/semana17/aula51/src/services/mailTransporter.ts new file mode 100644 index 0000000..1a493cb --- /dev/null +++ b/semana17/aula51/src/services/mailTransporter.ts @@ -0,0 +1,16 @@ +import nodemailer from 'nodemailer'; +import dotenv from "dotenv" + +dotenv.config() + +const transporter = nodemailer.createTransport({ + service: 'Gmail', + secure: false, + auth: { + user:process.env.NODEMAILER_USER, + pass: process.env.NODEMAILER_PASS + }, + tls: {ciphers: "SSLv3"} +}) + +export default transporter \ No newline at end of file diff --git a/semana17/aula51/src/types.ts b/semana17/aula51/src/types.ts index ea1594f..978303a 100644 --- a/semana17/aula51/src/types.ts +++ b/semana17/aula51/src/types.ts @@ -1,9 +1,19 @@ export type addressInfo = { - zipcode: string, - street: string, - number: number, - complement?: number, - neighbourhood: string, - city: string, - state: string + cep: string, + logradouro: string, + bairro: string, + localidade: string, + uf: string +} + +export type user = { + id: string + nome: string + cep: string + logradouro: string + numero: number + complemento?: string + bairro: string + localidade: string + uf: string } \ No newline at end of file diff --git a/semana17/aula51/tsconfig.json b/semana17/aula51/tsconfig.json index 8b53520..41834f8 100644 --- a/semana17/aula51/tsconfig.json +++ b/semana17/aula51/tsconfig.json @@ -67,6 +67,7 @@ /* Advanced Options */ "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ + "resolveJsonModule": true } }