diff --git a/src/handlers/implants.ts b/src/handlers/implants.ts index 0ce43923910cad100781848b29615f1e3e5fae25..42cd9beb5ae547a8cf3a2e0f932259ebba1f7156 100644 --- a/src/handlers/implants.ts +++ b/src/handlers/implants.ts @@ -1,176 +1,195 @@ -import { type Request, type Response } from 'express'; -import { implantsTable, purchasesTable, usersTable} from '@/db/schema'; -import { db } from "@/db"; -import { eq } from 'drizzle-orm'; -import { implantSchema, updateImplantSchema } from '@/validators/implantsValidator'; -import { error } from 'console'; - -export default class implant{ - static implantRequestValidation (req: Request){ - const validation = updateImplantSchema.safeParse(req.body); - return validation.success; - } - - static implantRequestUnzip (req: Request){ - return implantSchema.safeParse(req.body); - } - - static async getImplant (id: number){ - const searched = await db.select().from(implantsTable).where(eq(implantsTable.id, id)).limit(1); - return searched[0] || null; - } - - static async implantRead(req: Request, res: Response){ - if (!implant.implantRequestValidation(req)) - { - return res.status(400).json({ error: "Invalid Request"}); - } - - const { id } = req.params; - const parsedId = parseInt(id, 10); - if (isNaN(parsedId)) { - return res.status(400).json({ error: "ID inválido" }); - } - - const holder = await implant.getImplant(parsedId); - if (!holder) - { - return res.status(404).json({ error: "Not Found"}); - } - - return res.status(200).json(holder); - - } - - static async implantUpdate(req: Request, res: Response){ - if (!implant.implantRequestValidation(req)) - { - return res.status(400).json({ error: "Invalid Request"}); - } - - const { id } = req.params; - const parsedId = parseInt(id, 10); - if (isNaN(parsedId)) { - return res.status(400).json({ error: "ID inválido" }); - } - - const updated_implant = await implant.getImplant(parsedId); - if (!updated_implant) - { - return res.status(404).json({ error: "Not Found"}); - } - - const updates: Partial<typeof implantsTable.$inferInsert> = { - name: req.body.name || updated_implant.name, - price: req.body.price || updated_implant.price, - cyberCost: req.body.cyberCost || updated_implant.cyberCost, - bodyPart: req.body.bodyPart || updated_implant.bodyPart, - }; - - try{ - await db.update(implantsTable).set(updates).where(eq(implantsTable.id, parsedId)); - } catch (error) { - return res.status (500).json({ error: "Update User Error"}) - } - - return res.status(200).json({ message: "OK"}); - } - - static async implantDelete(req: Request, res: Response){ - if (!implant.implantRequestValidation(req)) - { - return res.status(400).json("Invalid Request"); - } - - const { id } = req.params; - const parsedId = parseInt(id, 10); - if (isNaN(parsedId)) { - return res.status(400).json({ error: "ID inválido" }); - } - - if (!implant.getImplant(parsedId)) - { - return res.status(404).json("Not Found"); - } - - try{ - await db.delete(implantsTable).where(eq(implantsTable.id, parsedId)); - return res.status(200).json({ message: "Implant removed successfully"}); - } catch (error) { - return res.status(500).json({ error: "Implant Removal Error"}); - } - } - - static async implantCreate(req: Request, res: Response){ - const implant_package = implant.implantRequestUnzip(req); - if (!implant_package.success) - { - return res.status(400).json("Invalid Request"); - } - - const { name, price, cyberCost, bodyPart } = implant_package.data; - - try{ - const brand_new = await db.insert(implantsTable).values({ - name, - price, - cyberCost, - bodyPart, - }).returning(); - - return res.status(200).json({ message: "Implant Creation Successfull", implant: brand_new}); - } catch (error) { - return res.status(500).json({ error: "User Creation Error"}); - } - } - - static async implantBuy (req: Request, res: Response): Promise<any>{ - try{ - const { buyer_id, product_id } = req.body; - - const user = await db.select().from(usersTable).where(eq(usersTable.id, buyer_id)); - const cyberPart = await db.select().from(implantsTable).where(eq(implantsTable.id, product_id)); - - if (!user || !cyberPart) - return res.status(404).json({ error: "User or implant not found" }); - - const bought = await db.select().from(purchasesTable).where(eq(purchasesTable.implant_id, product_id)) - if (bought.length > 0) - return res.status(404).json({ error: "Implant was already bought" }); - - var userMoney = parseFloat(user.money); - const implantPrice = parseFloat(cyberPart.price); - var userCyberPsychosis = parseInt(user.cyberpsychosis, 10); - const userCyberLimit = parseInt(user.cyberLimit, 10); - const implantCyberCost = parseInt(cyberPart.cyberCost, 10) - - if (userMoney < implantPrice) - return res.status(404).json({ error: "Insufficient money" }); - - userMoney -= implantPrice; - userCyberPsychosis += implantCyberCost; - - if (userCyberPsychosis >= userCyberLimit) - return res.status(404).json({ error: "Impossible to use implant, risk of cyberpsychosis is too high" }); - - const updated_user = await db.update(usersTable) - .set({ - money: userMoney.toString(), - cyberpsychosis: userCyberPsychosis.toString() - }).where(eq(usersTable.id, buyer_id)).returning(); - - const purchase = await db.insert(purchasesTable) - .values({ - user_id: buyer_id, - implant_id: product_id, - }).returning(); - - return res.status(200) - .json({ message: "Implant bought successfully", - purchase, user: updated_user }); - } catch (error) { - console.error(error); - return res.status(500).json({ error: "Erro ao realizar a compra" }); - } +import { type Request, type Response } from 'express' +import { implantsTable, purchasesTable, usersTable } from '@/db/schema' +import { db } from '@/db' +import { eq } from 'drizzle-orm' +import { implantSchema, updateImplantSchema } from '@/validators/implantsValidator' +import { error } from 'console' + +export default class implant { + static implantRequestValidation(req: Request) { + const validation = updateImplantSchema.safeParse(req.body) + return validation.success + } + + static implantRequestUnzip(req: Request) { + return implantSchema.safeParse(req.body) + } + + static async getImplant(id: number) { + const searched = await db.select().from(implantsTable).where(eq(implantsTable.id, id)).limit(1) + return searched[0] || null + } + + static async implantRead(req: Request, res: Response) { + if (!implant.implantRequestValidation(req)) { + return res.status(400).json({ error: 'Invalid Request' }) } + + const { id } = req.params + const parsedId = parseInt(id, 10) + if (isNaN(parsedId)) { + return res.status(400).json({ error: 'ID inválido' }) + } + + const holder = await implant.getImplant(parsedId) + if (!holder) { + return res.status(404).json({ error: 'Not Found' }) + } + + return res.status(200).json(holder) + } + + static async implantReadAll(req: Request, res: Response) { + if (!implant.implantRequestValidation(req)) { + return res.status(400).json({ error: 'Invalid Request' }) + } + try { + const implants = await db.select().from(implantsTable) + res.json(implants) + } catch (error) { + res.status(404).json({ error: error }) + } + } + + static async implantTransactionData(req: Request, res: Response) { + if (!implant.implantRequestValidation(req)) { + return res.status(400).json({ error: 'Invalid Request ' }) + } + try { + const transactionData = await db.select().from(purchasesTable) + res.json(transactionData) + } catch (error) { + res.status(404).json({ error: error }) + } + } + + static async implantUpdate(req: Request, res: Response) { + if (!implant.implantRequestValidation(req)) { + return res.status(400).json({ error: 'Invalid Request' }) + } + + const { id } = req.params + const parsedId = parseInt(id, 10) + if (isNaN(parsedId)) { + return res.status(400).json({ error: 'ID inválido' }) + } + + const updated_implant = await implant.getImplant(parsedId) + if (!updated_implant) { + return res.status(404).json({ error: 'Not Found' }) + } + + const updates: Partial<typeof implantsTable.$inferInsert> = { + name: req.body.name || updated_implant.name, + price: req.body.price || updated_implant.price, + cyberCost: req.body.cyberCost || updated_implant.cyberCost, + bodyPart: req.body.bodyPart || updated_implant.bodyPart, + } + + try { + await db.update(implantsTable).set(updates).where(eq(implantsTable.id, parsedId)) + } catch (error) { + return res.status(500).json({ error: 'Update User Error' }) + } + + return res.status(200).json({ message: 'OK' }) + } + + static async implantDelete(req: Request, res: Response) { + if (!implant.implantRequestValidation(req)) { + return res.status(400).json('Invalid Request') + } + + const { id } = req.params + const parsedId = parseInt(id, 10) + if (isNaN(parsedId)) { + return res.status(400).json({ error: 'ID inválido' }) + } + + if (!implant.getImplant(parsedId)) { + return res.status(404).json('Not Found') + } + + try { + await db.delete(implantsTable).where(eq(implantsTable.id, parsedId)) + return res.status(200).json({ message: 'Implant removed successfully' }) + } catch (error) { + return res.status(500).json({ error: 'Implant Removal Error' }) + } + } + + static async implantCreate(req: Request, res: Response) { + const implant_package = implant.implantRequestUnzip(req) + if (!implant_package.success) { + return res.status(400).json('Invalid Request') + } + + const { name, price, cyberCost, bodyPart } = implant_package.data + + try { + const brand_new = await db + .insert(implantsTable) + .values({ + name, + price, + cyberCost, + bodyPart, + }) + .returning() + + return res.status(200).json({ message: 'Implant Creation Successfull', implant: brand_new }) + } catch (error) { + return res.status(500).json({ error: 'User Creation Error' }) + } + } + + static async implantBuy(req: Request, res: Response): Promise<any> { + try { + const { buyer_id, product_id } = req.body + + const user = await db.select().from(usersTable).where(eq(usersTable.id, buyer_id)) + const cyberPart = await db.select().from(implantsTable).where(eq(implantsTable.id, product_id)) + + if (!user || !cyberPart) return res.status(404).json({ error: 'User or implant not found' }) + + const bought = await db.select().from(purchasesTable).where(eq(purchasesTable.implant_id, product_id)) + if (bought.length > 0) return res.status(404).json({ error: 'Implant was already bought' }) + + var userMoney = parseFloat(user[0].money) + const implantPrice = parseFloat(cyberPart[0].price) + var userCyberPsychosis = parseInt(user[0].cyberpsychosis, 10) + const userCyberLimit = parseInt(user[0].cyberLimit, 10) + const implantCyberCost = parseInt(cyberPart[0].cyberCost, 10) + + if (userMoney < implantPrice) return res.status(404).json({ error: 'Insufficient money' }) + + userMoney -= implantPrice + userCyberPsychosis += implantCyberCost + + if (userCyberPsychosis >= userCyberLimit) + return res.status(404).json({ error: 'Impossible to use implant, risk of cyberpsychosis is too high' }) + + const updated_user = await db + .update(usersTable) + .set({ + money: userMoney.toString(), + cyberpsychosis: userCyberPsychosis.toString(), + }) + .where(eq(usersTable.id, buyer_id)) + .returning() + + const purchase = await db + .insert(purchasesTable) + .values({ + user_id: buyer_id, + implant_id: product_id, + }) + .returning() + + return res.status(200).json({ message: 'Implant bought successfully', purchase, user: updated_user }) + } catch (error) { + console.error(error) + return res.status(500).json({ error: 'Erro ao realizar a compra' }) + } + } } diff --git a/src/index.ts b/src/index.ts index e73cc1723738acc32cb5ba4dbc4fbd860730b322..86ea5d69db84758684d1c1bd27ad228cbfdabeca 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,19 +1,21 @@ import express, { urlencoded, json } from 'express' import dotenv from 'dotenv' -import User from './handlers/user'; +import User from './handlers/user' import implant from './handlers/implants' -import { tokenAuthenticator} from '@/middleware/auth' +import { tokenAuthenticator } from '@/middleware/auth' import cors from 'cors' // Carregar variáveis de ambiente dotenv.config() const app = express() -app.use(cors({ - origin: 'http://localhost:5173', - methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], - allowedHeaders: ['Content-Type', 'Authorization'], -})); +app.use( + cors({ + origin: 'http://localhost:5173', + methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + allowedHeaders: ['Content-Type', 'Authorization'], + }) +) // Middlewares app.use(urlencoded({ extended: true })) @@ -32,10 +34,13 @@ app.get('/getImplant/:id', implant.implantRead) app.put('/updateImplant/:id', tokenAuthenticator, implant.implantUpdate) app.delete('/deleteImplant/:id', tokenAuthenticator, implant.implantDelete) app.post('/purchase', tokenAuthenticator, implant.implantBuy) +app.get('/getAllImplant', implant.implantReadAll) +//rota de dados de compras +app.get('/getTransactionData', implant.implantTransactionData) // Definir a porta e iniciar o servidor const PORT = process.env['PORT'] || 3000 app.listen(PORT, () => { console.log(`🚀 Servidor rodando na porta ${PORT}`) -}) \ No newline at end of file +})