diff --git a/Backend/Semana 2/projeto-backend-semana2/template-express-knex/.DS_Store b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/.DS_Store differ diff --git a/Backend/Semana 2/projeto-backend-semana2/template-express-knex/.gitignore b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/.gitignore new file mode 100644 index 0000000..42fa6fe --- /dev/null +++ b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/.gitignore @@ -0,0 +1,4 @@ +node_modules +package-lock.json +build +.env diff --git a/Backend/Semana 2/projeto-backend-semana2/template-express-knex/package.json b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/package.json new file mode 100644 index 0000000..b45f603 --- /dev/null +++ b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/package.json @@ -0,0 +1,28 @@ +{ + "name": "aula-back-filtros", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "tsc && node ./build/index.js", + "dev": "ts-node-dev ./src/index.ts", + "build": "tsc" + }, + "author": "", + "license": "ISC", + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^8.2.0", + "express": "4.17.0", + "knex": "^0.21.1", + "mysql": "^2.18.1" + }, + "devDependencies": { + "@types/cors": "^2.8.8", + "@types/express": "4.17.0", + "@types/knex": "^0.16.1", + "@types/node": "^13.7.7", + "ts-node-dev": "^1.0.0-pre.44", + "typescript": "^3.8.3" + } +} diff --git a/Backend/Semana 2/projeto-backend-semana2/template-express-knex/src/.DS_Store b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/src/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/src/.DS_Store differ diff --git a/Backend/Semana 2/projeto-backend-semana2/template-express-knex/src/index.ts b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/src/index.ts new file mode 100644 index 0000000..d0309fe --- /dev/null +++ b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/src/index.ts @@ -0,0 +1,132 @@ +import express, { Express, Request, Response } from "express"; +import knex from "knex"; +import cors from "cors"; +import dotenv from "dotenv"; +import { AddressInfo } from "net"; + +dotenv.config(); + +export const connection = knex({ + client: "mysql", + connection: { + host: process.env.DB_HOST, + port: 3306, + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME + } +}) + +const app: Express = express(); +app.use(express.json()); +app.use(cors()) + +//ENDPOINT 1 - CRIA USUÁRIOS + +const createUser = async (name: string, nickname: string, email: string):Promise => { + + try { + await connection + .insert({ + id: String(Date.now()), + name, + nickname, + email + }) + .into("TodoListUser "); + } catch (error) { + console.log(error) + } + +} + +app.post("/user", async (req: Request, res: Response) => { + try { + + //Validação todos os campos obrigatórios + const keys = Object.keys(req.body) + + for (const key of keys) { + if (req.body[key] == "") + return res.status(400).send({ message: "Por gentileza preencha todos os campos corretamente!"}) + } + + const {name, nickname, email} = req.body + + await createUser(name, nickname, email); + + res.status(200).send("Usuário criado com sucesso"); + } catch (err) { + res.status(400).send({ + message: err.message, + }); + } + }); + +// ENDPOINT 2 - PEGA USUÁRIOS PELO ID + + const getUserById = async (id: string): Promise => { + const result = await connection.raw(` + SELECT * FROM TodoListUser WHERE id = "${id}" + `); + return result; + }; + + app.get("/user/:id", async (req: Request, res: Response) => { + try { + const id = req.params.id + const user = await getUserById(id); + + res.status(200).send(user); + } catch (err) { + res.status(400).send({ + message: err.message, + }); + } + }); + + + //ENDPOINT 3 - EDITAR USUÁRIO + + const updateUser = async (id: string, name: string, nickname: string, email: string): Promise => { + const result = await connection.raw(` + UPDATE TodoListUser + SET + name = "${name}", + nickname = "${nickname}", + email = "${email}" + WHERE + id = ${id} + `) + return result[0] + } + + app.post("user/edit/:id", async (req: Request, res: Response) => { + let errorCode: number = 400; + try{ + const id = req.params.id + const name = req.body.name + const nickname = req.body.nickname + const email = req.body.email + + if(!req.params.id || !req.body.name || !req.body.nickname || req.body.email){ + errorCode = 422 + throw new Error("Dados faltantes ou incorretos. Tente novamente.") + } + const result = await updateUser(id, name, nickname, email) + res.status(200).send(result) + } catch (error) { + res.status(400).send({ + message: error.message, + }); + } + }) + +const server = app.listen(process.env.PORT || 3003, () => { + if (server) { + const address = server.address() as AddressInfo; + console.log(`Server is running in http://localhost:${address.port}`); + } else { + console.error(`Failure upon starting server.`); + } +}); diff --git a/Backend/Semana 2/projeto-backend-semana2/template-express-knex/tsconfig.json b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/tsconfig.json new file mode 100644 index 0000000..b520b3a --- /dev/null +++ b/Backend/Semana 2/projeto-backend-semana2/template-express-knex/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, + "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, + "outDir": "./build" /* Redirect output structure to the directory. */, + "rootDir": "./" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */, + "strict": true /* Enable all strict type-checking options. */, + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + } +}