Skip to content
Snippets Groups Projects
Select Git revision
  • develop default
  • issue-4/tela-implantes-user-back
  • issue-13/buy-implant
  • main protected
4 results

implants.ts

Blame
  • Forked from C3SL / treinamento-2025.1-backend
    53 commits ahead of the upstream repository.
    implants.ts 6.28 KiB
    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, success: true })
        } catch (error) {
          console.error(error)
          return res.status(500).json({ error: 'Erro ao realizar a compra' })
        }
      }
    }