Skip to content
Snippets Groups Projects

Issue#7: ADD All routes, create route broken

Merged RICARDO PRADO FARIA requested to merge issue-7/implants-crud into develop
3 files
+ 126
10
Compare changes
  • Side-by-side
  • Inline
Files
3
+ 107
0
import { type Request, type Response } from 'express';
import { implants } from '@/db/schema';
import { db } from "@/db";
import { eq } from 'drizzle-orm';
import { implantSchema } from '@/validators/implantsValidator';
export default class implant{
static implantRequestValidation (req: Request){
const validation = implantSchema.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(implants).where(eq(implants.id, id)).limit(1);
return searched[0] || null;
}
static async implantRead(id: number, req: Request, res: Response){
if (!this.implantRequestValidation(req))
{
return res.status(400).json({ error: "Invalid Request"});
}
const holder = await this.getImplant(id);
if (!holder)
{
return res.status(404).json({ error: "Not Found"});
}
return res.status(200).json(holder);
}
static async implantUpdate(id: number, req: Request, res: Response){
if (!this.implantRequestValidation(req))
{
return res.status(400).json({ error: "Invalid Request"});
}
const updated_implant = await this.getImplant(id);
if (!updated_implant)
{
return res.status(404).json({ error: "Not Found"});
}
const updates: Partial<typeof implants.$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(implants).set(updates).where(eq(implants.id, id));
} catch (error) {
return res.status (500).json({ error: "Update User Error"})
}
return res.status(200).json({ message: "OK"});
}
static async implantDelete(id: number, req: Request, res: Response){
if (!this.implantRequestValidation(req))
{
return res.status(400).json("Invalid Request");
}
if (!this.getImplant(id))
{
return res.status(404).json("Not Found");
}
try{
await db.delete(implants).where(eq(implants.id, id));
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 = this.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(implants).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"});
}
}
}
Loading