diff --git a/src/handlers/user.ts b/src/handlers/user.ts index ab66000dd7578881cb16722f39f7b94fcd45fb92..1b8651e5e5e777e7bda6c7d68db1dc325381ce3b 100644 --- a/src/handlers/user.ts +++ b/src/handlers/user.ts @@ -7,23 +7,64 @@ import bcrypt from "bcryptjs"; import { z } from 'zod'; export default class User{ - static userRequestValidation (req: Request){ + static userRequestValidation (req: Request){ //valida a requisição do usuário const validation = userSchema.safeParse(req.body); return validation.success; } - static async userExistenceValidation (id: number){ + static async userExistenceValidation (id: number){ //verifica se o usuário existe const user = await db.select().from(usersTable).where(eq(usersTable.id, id)).limit(1); return user.length > 0; } + static async getUser(id: number){ //retorna o usuário presente no db + var user = await db.select().from(usersTable).where(eq(usersTable.id, id)).limit(1); + return user; + } + + + static async updateUser (id: number, req: Request, res:Response){ + if (!this.userRequestValidation(req)) + { + return res.status(400).json({ erro: "Invalid Request" }); + } + + if (!(await this.userExistenceValidation(id))) + { + return res.status(404).json({ error: "Not Found "}); + } + + let hashedPassword = req.body.password; + if (req.body.password) + { + hashedPassword = await bcrypt.hash(req.body.password, 10); + } + + const user_updated = await this.getUser(id); + + const updates: Partial<typeof usersTable.$inferInsert> = { + name: req.body.name || user_updated.name; + password: hashedPassword || user_updated.password; + email: req.body.email || user_updated.email; + birthday: req.body.birthday || user_updated.birthday; + cpf: req.body.cpf || user_updated.cpf; + money: req.body.money || user_updated.money; + cyberpsychosis: req.body.cyberpsychosis || user_updated.cyberpsychosis; + cyberLimit: req.body.cyberLimit || user_updated.cyberLimit; + }; + + await db.update(usersTable).set(updates).where(eq(usersTable.id, id)); + + return res.status(200).json({ message: "User Updated Successfully "}); + } + static async deleteUser (id: number, req: Request, res: Response){ if (!this.userRequestValidation(req)) { return res.status(400).json({ error: "Invalid Request" });; } - if (!this.userExistenceValidation(id)) + if (!(await this.userExistenceValidation(id))) { return res.status(404).json({ error: "Not Found"}); }