Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions semana25/case-ambulnz-fullstack/ambulnz-backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
build
.env
1,127 changes: 1,127 additions & 0 deletions semana25/case-ambulnz-fullstack/ambulnz-backend/package-lock.json

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions semana25/case-ambulnz-fullstack/ambulnz-backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "case-ambulnz",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev-start": "ts-node-dev ./src/index.ts",
"start": "tsc && node --inspect ./build/index.js",
"migrations": "ts-node-dev ./src/data/migrations.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.2",
"knex": "^1.0.3",
"mysql": "^2.18.1"
},
"devDependencies": {
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/knex": "^0.16.1",
"@types/node": "^17.0.17",
"ts-node-dev": "^1.1.8",
"typescript": "^4.5.5"
}
}
17 changes: 17 additions & 0 deletions semana25/case-ambulnz-fullstack/ambulnz-backend/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import express from "express"
import cors from "cors"
import { AddressInfo } from "net"

export const app = express()

app.use(express.json())
app.use(cors())

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.`)
}
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import knex from "knex"
import dotenv from "dotenv"

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_SCHEMA,
multipleStatements: true
}
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { connection } from "./connection"

const printError = (error: any) => { console.log(error.sqlMessage || error.message) }

const createTable = () => connection.raw(`
CREATE TABLE IF NOT EXISTS LabePizza (
id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price FLOAT NOT NULL,
ingredients VARCHAR(255) NOT NULL
);

CREATE TABLE IF NOT EXISTS LabePizza_Orders (
id VARCHAR(255) PRIMARY KEY,
pizza_id VARCHAR(255) NOT NULL,
quantity INT NOT NULL,
total_price FLOAT NOT NULL,
FOREIGN KEY (pizza_id) REFERENCES LabePizza (id)
);
`)
.then(() => { console.log("Created Tables!") })
.catch(printError)

const insertUsers = () => connection.raw(`
INSERT INTO LabePizza (id, name, price, ingredients) VALUES (1,'4 Queijos','9','Catupiry, Mussarela, Provolone e Parmessão');
INSERT INTO LabePizza (id, name, price, ingredients) VALUES (2,'Baiana','8','Calabresa Moída, Pimenta, Bacon e Cebola');
INSERT INTO LabePizza (id, name, price, ingredients) VALUES (3,'Frango com Catupiry','7.5','Frango e Catupiry');
INSERT INTO LabePizza (id, name, price, ingredients) VALUES (4,'Portuguesa','9','Mussarela, Presunto, Ovos, Ervilha e Cebola');
INSERT INTO LabePizza (id, name, price, ingredients) VALUES (5,'Romeu e Julieta','10','Goiabada e Mussarela');
`)
.then(() => { console.log("Created Pizzas!") })
.catch(printError)

const closeConnection = () => { connection.destroy() }

createTable()
.then(insertUsers)
.finally(closeConnection)
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { connection } from "../data/connection"
import { Request, Response } from "express"
import { Pizza } from "../types"

export const getAllPizzas = async (req: Request, res: Response): Promise<void> => {
try {
const pizzas: Pizza[] = await connection("LabePizza")

res.send({ pizzas })

} catch (error:any) {
res.status(400).send({ message: error.message })
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { connection } from "../data/connection"
import { Request, Response } from "express"
import { Order } from "../types"

export const getListOrders = async (req: Request, res: Response): Promise<void> => {
try {
const listOrders: Order[] = await connection("LabePizza_Orders")
.select(
"LabePizza_Orders.id",
"LabePizza.name",
"LabePizza_Orders.quantity")
.innerJoin("LabePizza", "LabePizza.id", "=", "LabePizza_Orders.pizza_id")

res.send({ listOrders })

} catch (error:any) {
res.status(400).send({ message: error.message })
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { connection } from "../data/connection"
import { Request, Response } from "express"
import { Order } from "../types"

export const getOrderById = async (req: Request, res: Response): Promise<void> => {
try {
const { id } = req.params

const result: Order[] = await connection("LabePizza_Orders").where({ "LabePizza_Orders.id": id })

const order = result

if (!order) {
throw new Error("Pedido não encontrado!")
}

const orderDetail: Order[] = await connection("LabePizza_Orders")
.select(
"LabePizza_Orders.id",
"LabePizza_Orders.pizza_id",
"LabePizza.name",
"LabePizza_Orders.quantity",
"LabePizza_Orders.total_price")
.innerJoin("LabePizza", "LabePizza.id", "=", "LabePizza_Orders.pizza_id")
.where({ "LabePizza_Orders.id": id })

res.status(200).send({ orderDetail })

} catch (error:any) {
res.status(400).send({ message: error.message })
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { connection } from "../data/connection"
import { Request, Response } from "express"
import { Pizza, Order } from "../types"

export const registerOrders = async (req: Request, res: Response): Promise<void> => {
try {
const { pizza_id, quantity } = req.body

if (!pizza_id || !quantity) {
throw new Error("Preencher todos os parâmetros.")
}

const [pizza]: Pizza[] = await connection("LabePizza")
.select()
.where({ id: pizza_id })

if (!pizza) {
throw new Error("Pizza não encontrada. (pizza_id)!")
}

const total_price = pizza.price * quantity

const order: Order = {
id: Date.now().toString(),
pizza_id,
quantity,
total_price
}

await connection("LabePizza_Orders").insert(order)

res.status(201).send({ message: "Pedido realizado com sucesso!" })

} catch (error: any) {
res.status(400).send({ message: error.message })
}
}
13 changes: 13 additions & 0 deletions semana25/case-ambulnz-fullstack/ambulnz-backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { app } from "./app"
import { getAllPizzas } from "./endpoints/getAllPizzas"
import { getListOrders } from "./endpoints/getListOrders"
import { getOrderById } from "./endpoints/getOrderById"
import { registerOrders } from "./endpoints/registerOrder"

app.get("/pizzas", getAllPizzas)

app.get("/orders", getListOrders)

app.get("/orders/:id", getOrderById)

app.post("/orders", registerOrders)
13 changes: 13 additions & 0 deletions semana25/case-ambulnz-fullstack/ambulnz-backend/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export type Pizza = {
id: string
name: string
price: number
ingredients: string
}

export type Order = {
id: string
pizza_id: string
quantity: number
total_price: number
}
12 changes: 12 additions & 0 deletions semana25/case-ambulnz-fullstack/ambulnz-backend/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"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": "./src" /* 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. */,
"resolveJsonModule": true
}
}