From fd703d51b62f15ebe215b4866f1832abb6562443 Mon Sep 17 00:00:00 2001 From: apsr23 <apsr23@inf.ufpr.br> Date: Thu, 13 Mar 2025 11:35:00 -0300 Subject: [PATCH] apagar arquivos --- .env.example | 14 - .../migrations/0001_flat_captain_america.sql | 26 -- src/db/migrations/0001_happy_tomas.sql | 1 - src/db/migrations/0002_serious_arclight.sql | 10 - src/db/migrations/0003_goofy_zodiak.sql | 3 - src/db/migrations/meta/0001_snapshot.json | 200 ------------- src/db/migrations/meta/0002_snapshot.json | 273 ----------------- src/db/migrations/meta/0003_snapshot.json | 281 ------------------ src/db/migrations/meta/_journal.json | 34 --- src/db/schema.ts | 59 ---- src/handlers/implants.ts | 218 -------------- src/handlers/user.ts | 206 ------------- src/index.ts | 13 - src/middleware/auth.ts | 31 -- src/validators/implantsValidator.ts | 28 -- src/validators/userValidator.ts | 25 -- 16 files changed, 1422 deletions(-) delete mode 100644 .env.example delete mode 100644 src/db/migrations/0001_flat_captain_america.sql delete mode 100644 src/db/migrations/0001_happy_tomas.sql delete mode 100644 src/db/migrations/0002_serious_arclight.sql delete mode 100644 src/db/migrations/0003_goofy_zodiak.sql delete mode 100644 src/db/migrations/meta/0001_snapshot.json delete mode 100644 src/db/migrations/meta/0002_snapshot.json delete mode 100644 src/db/migrations/meta/0003_snapshot.json delete mode 100644 src/db/migrations/meta/_journal.json diff --git a/.env.example b/.env.example deleted file mode 100644 index da1acaa..0000000 --- a/.env.example +++ /dev/null @@ -1,14 +0,0 @@ -# code config -NODE_ENV=development -PORT=3000 - -# db config -DB_HOST=localhost -DB_USER=postgres -DB_PASSWORD=123mudar -DB_NAME=treinamento -DB_PORT=5432 -DB_URL=postgresql://postgres:123mudar@localhost:5432/treinamento - -# secret -APP_SECRET=hash_aleatoria_bem_longa diff --git a/src/db/migrations/0001_flat_captain_america.sql b/src/db/migrations/0001_flat_captain_america.sql deleted file mode 100644 index 5b0cb44..0000000 --- a/src/db/migrations/0001_flat_captain_america.sql +++ /dev/null @@ -1,26 +0,0 @@ -CREATE TABLE "implants" ( - "id" serial PRIMARY KEY NOT NULL, - "name" varchar(255) NOT NULL, - "created_at" timestamp DEFAULT now() NOT NULL, - "price" numeric NOT NULL, - "cyberCost" numeric DEFAULT '5' NOT NULL, - "bodyPart" varchar(255) NOT NULL, - "updated_at" timestamp DEFAULT now() NOT NULL, - CONSTRAINT "implants_id_unique" UNIQUE("id") -); ---> statement-breakpoint -CREATE TABLE "users" ( - "id" serial PRIMARY KEY NOT NULL, - "name" varchar(255) NOT NULL, - "password" varchar(255) NOT NULL, - "email" varchar(255) NOT NULL, - "birthday" timestamp NOT NULL, - "cpf" varchar(11) NOT NULL, - "money" numeric DEFAULT '0' NOT NULL, - "cyberpsychosis" numeric, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp DEFAULT now() NOT NULL, - CONSTRAINT "users_id_unique" UNIQUE("id"), - CONSTRAINT "users_email_unique" UNIQUE("email"), - CONSTRAINT "users_cpf_unique" UNIQUE("cpf") -); diff --git a/src/db/migrations/0001_happy_tomas.sql b/src/db/migrations/0001_happy_tomas.sql deleted file mode 100644 index 21e4260..0000000 --- a/src/db/migrations/0001_happy_tomas.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE TYPE "public"."bodyParts" AS ENUM('FrontalCortex', 'OperatingSystem', 'Arms', 'Skeleton', 'NervousSystem', 'IntegumentarySystem', 'Face', 'Hands', 'CirculatorySystem', 'Legs'); \ No newline at end of file diff --git a/src/db/migrations/0002_serious_arclight.sql b/src/db/migrations/0002_serious_arclight.sql deleted file mode 100644 index 445eb0e..0000000 --- a/src/db/migrations/0002_serious_arclight.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE TABLE "purchases" ( - "id" serial PRIMARY KEY NOT NULL, - "user_id" integer NOT NULL, - "implant_id" integer NOT NULL, - "created_at" timestamp DEFAULT now() NOT NULL, - CONSTRAINT "purchases_id_unique" UNIQUE("id") -); ---> statement-breakpoint -ALTER TABLE "purchases" ADD CONSTRAINT "purchases_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "purchases" ADD CONSTRAINT "purchases_implant_id_implants_id_fk" FOREIGN KEY ("implant_id") REFERENCES "public"."implants"("id") ON DELETE no action ON UPDATE no action; \ No newline at end of file diff --git a/src/db/migrations/0003_goofy_zodiak.sql b/src/db/migrations/0003_goofy_zodiak.sql deleted file mode 100644 index 27c81dd..0000000 --- a/src/db/migrations/0003_goofy_zodiak.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE "users" ALTER COLUMN "cyberpsychosis" SET DEFAULT '0';--> statement-breakpoint -ALTER TABLE "users" ALTER COLUMN "cyberpsychosis" SET NOT NULL;--> statement-breakpoint -ALTER TABLE "users" ADD COLUMN "cyberLimit" numeric DEFAULT '100' NOT NULL; \ No newline at end of file diff --git a/src/db/migrations/meta/0001_snapshot.json b/src/db/migrations/meta/0001_snapshot.json deleted file mode 100644 index 7df26f0..0000000 --- a/src/db/migrations/meta/0001_snapshot.json +++ /dev/null @@ -1,200 +0,0 @@ -{ - "id": "91d20893-78f7-4fb7-8e88-188da52e82a4", - "prevId": "52d6596f-1582-4551-a4d4-18d70acf89e6", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.implants": { - "name": "implants", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "price": { - "name": "price", - "type": "numeric", - "primaryKey": false, - "notNull": true - }, - "cyberCost": { - "name": "cyberCost", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'5'" - }, - "bodyPart": { - "name": "bodyPart", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "implants_id_unique": { - "name": "implants_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "password": { - "name": "password", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "email": { - "name": "email", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "birthday": { - "name": "birthday", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "cpf": { - "name": "cpf", - "type": "varchar(11)", - "primaryKey": false, - "notNull": true - }, - "money": { - "name": "money", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'0'" - }, - "cyberpsychosis": { - "name": "cyberpsychosis", - "type": "numeric", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_id_unique": { - "name": "users_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - }, - "users_email_unique": { - "name": "users_email_unique", - "nullsNotDistinct": false, - "columns": [ - "email" - ] - }, - "users_cpf_unique": { - "name": "users_cpf_unique", - "nullsNotDistinct": false, - "columns": [ - "cpf" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.bodyParts": { - "name": "bodyParts", - "schema": "public", - "values": [ - "FrontalCortex", - "OperatingSystem", - "Arms", - "Skeleton", - "NervousSystem", - "IntegumentarySystem", - "Face", - "Hands", - "CirculatorySystem", - "Legs" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/src/db/migrations/meta/0002_snapshot.json b/src/db/migrations/meta/0002_snapshot.json deleted file mode 100644 index 046cbfd..0000000 --- a/src/db/migrations/meta/0002_snapshot.json +++ /dev/null @@ -1,273 +0,0 @@ -{ - "id": "5c95e34f-48d6-4848-9024-414b0f3ecbf9", - "prevId": "91d20893-78f7-4fb7-8e88-188da52e82a4", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.implants": { - "name": "implants", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "price": { - "name": "price", - "type": "numeric", - "primaryKey": false, - "notNull": true - }, - "cyberCost": { - "name": "cyberCost", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'5'" - }, - "bodyPart": { - "name": "bodyPart", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "implants_id_unique": { - "name": "implants_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.purchases": { - "name": "purchases", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "implant_id": { - "name": "implant_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": { - "purchases_user_id_users_id_fk": { - "name": "purchases_user_id_users_id_fk", - "tableFrom": "purchases", - "tableTo": "users", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - }, - "purchases_implant_id_implants_id_fk": { - "name": "purchases_implant_id_implants_id_fk", - "tableFrom": "purchases", - "tableTo": "implants", - "columnsFrom": [ - "implant_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "purchases_id_unique": { - "name": "purchases_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "password": { - "name": "password", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "email": { - "name": "email", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "birthday": { - "name": "birthday", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "cpf": { - "name": "cpf", - "type": "varchar(11)", - "primaryKey": false, - "notNull": true - }, - "money": { - "name": "money", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'0'" - }, - "cyberpsychosis": { - "name": "cyberpsychosis", - "type": "numeric", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_id_unique": { - "name": "users_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - }, - "users_email_unique": { - "name": "users_email_unique", - "nullsNotDistinct": false, - "columns": [ - "email" - ] - }, - "users_cpf_unique": { - "name": "users_cpf_unique", - "nullsNotDistinct": false, - "columns": [ - "cpf" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.bodyParts": { - "name": "bodyParts", - "schema": "public", - "values": [ - "FrontalCortex", - "OperatingSystem", - "Arms", - "Skeleton", - "NervousSystem", - "IntegumentarySystem", - "Face", - "Hands", - "CirculatorySystem", - "Legs" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/src/db/migrations/meta/0003_snapshot.json b/src/db/migrations/meta/0003_snapshot.json deleted file mode 100644 index 70754f7..0000000 --- a/src/db/migrations/meta/0003_snapshot.json +++ /dev/null @@ -1,281 +0,0 @@ -{ - "id": "6695494c-d75d-40d4-a282-6d10980c71de", - "prevId": "5c95e34f-48d6-4848-9024-414b0f3ecbf9", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.implants": { - "name": "implants", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "price": { - "name": "price", - "type": "numeric", - "primaryKey": false, - "notNull": true - }, - "cyberCost": { - "name": "cyberCost", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'5'" - }, - "bodyPart": { - "name": "bodyPart", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "implants_id_unique": { - "name": "implants_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.purchases": { - "name": "purchases", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "implant_id": { - "name": "implant_id", - "type": "integer", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": { - "purchases_user_id_users_id_fk": { - "name": "purchases_user_id_users_id_fk", - "tableFrom": "purchases", - "tableTo": "users", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - }, - "purchases_implant_id_implants_id_fk": { - "name": "purchases_implant_id_implants_id_fk", - "tableFrom": "purchases", - "tableTo": "implants", - "columnsFrom": [ - "implant_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "no action", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "purchases_id_unique": { - "name": "purchases_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.users": { - "name": "users", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "serial", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "password": { - "name": "password", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "email": { - "name": "email", - "type": "varchar(255)", - "primaryKey": false, - "notNull": true - }, - "birthday": { - "name": "birthday", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "cpf": { - "name": "cpf", - "type": "varchar(11)", - "primaryKey": false, - "notNull": true - }, - "money": { - "name": "money", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'0'" - }, - "cyberpsychosis": { - "name": "cyberpsychosis", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'0'" - }, - "cyberLimit": { - "name": "cyberLimit", - "type": "numeric", - "primaryKey": false, - "notNull": true, - "default": "'100'" - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "users_id_unique": { - "name": "users_id_unique", - "nullsNotDistinct": false, - "columns": [ - "id" - ] - }, - "users_email_unique": { - "name": "users_email_unique", - "nullsNotDistinct": false, - "columns": [ - "email" - ] - }, - "users_cpf_unique": { - "name": "users_cpf_unique", - "nullsNotDistinct": false, - "columns": [ - "cpf" - ] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": { - "public.bodyParts": { - "name": "bodyParts", - "schema": "public", - "values": [ - "FrontalCortex", - "OperatingSystem", - "Arms", - "Skeleton", - "NervousSystem", - "IntegumentarySystem", - "Face", - "Hands", - "CirculatorySystem", - "Legs" - ] - } - }, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} \ No newline at end of file diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json deleted file mode 100644 index 7bb40de..0000000 --- a/src/db/migrations/meta/_journal.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "version": "7", - "dialect": "postgresql", - "entries": [ - { - "idx": 0, - "version": "7", - "when": 1741130659285, - "tag": "0001_flat_captain_america", - "breakpoints": true - }, - { - "idx": 1, - "version": "7", - "when": 1741189883348, - "tag": "0001_happy_tomas", - "breakpoints": true - }, - { - "idx": 2, - "version": "7", - "when": 1741214301943, - "tag": "0002_serious_arclight", - "breakpoints": true - }, - { - "idx": 3, - "version": "7", - "when": 1741216892624, - "tag": "0003_goofy_zodiak", - "breakpoints": true - } - ] -} \ No newline at end of file diff --git a/src/db/schema.ts b/src/db/schema.ts index becda21..e69de29 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -1,59 +0,0 @@ -import { sql } from 'drizzle-orm' -import { pgEnum, pgTable, serial, numeric, timestamp, varchar, integer } from 'drizzle-orm/pg-core' - -export const userTable = pgTable('users', { - id: serial('id').primaryKey().unique().notNull(), - name: varchar('name', { length: 255 }).notNull(), - password: varchar('password', { length: 255 }).notNull(), - email: varchar('email', { length: 255 }).unique().notNull(), - birthday: timestamp('birthday', { mode: 'string' }).notNull(), - cpf: varchar('cpf', { length: 11 }).unique().notNull(), - money: numeric('money').notNull().default('0'), - cyberpsychosis: numeric('cyberpsychosis').notNull().default('0'), - cyberLimit: numeric('cyberLimit').notNull().default('100'), - createdAt: timestamp('created_at', { mode: 'string' }).notNull().defaultNow(), - updatedAt: timestamp('updated_at', { mode: 'string' }) - .notNull() - .defaultNow() - .$onUpdate(() => sql`current_timestamp`), -}) - -export const bodyParts = pgEnum('bodyParts', [ - 'FrontalCortex', - 'OperatingSystem', - 'Arms', - 'Skeleton', - 'NervousSystem', - 'IntegumentarySystem', - 'Face', - 'Hands', - 'CirculatorySystem', - 'Legs', -]) - -export const implantsTable = pgTable('implants', { - id: serial('id').primaryKey().unique().notNull(), - name: varchar('name', { length: 255 }).notNull(), - createdAt: timestamp('created_at', { mode: 'string' }).notNull().defaultNow(), - price: numeric('price').notNull(), - cyberCost: numeric('cyberCost').notNull().default('5'), - bodyPart: varchar('bodyPart', { length: 255 }).notNull(), - updatedAt: timestamp('updated_at', { mode: 'string' }) - .notNull() - .defaultNow() - .$onUpdate(() => sql`current_timestamp`), -}) - -export const purchases = pgTable('purchases', { - id: serial('id').primaryKey().unique().notNull(), - - // chaves estrangeiras - user_id: integer('user_id') - .references(() => userTable.id) - .notNull(), - implant_id: integer('implant_id') - .references(() => implantsTable.id) - .notNull(), - - created_at: timestamp('created_at', { mode: 'string' }).notNull().defaultNow(), -}) diff --git a/src/handlers/implants.ts b/src/handlers/implants.ts index 48bab80..e69de29 100644 --- a/src/handlers/implants.ts +++ b/src/handlers/implants.ts @@ -1,218 +0,0 @@ -import { type Request, type Response } from 'express' -import { db } from '@/db' -import { implantsTable, purchases, userTable } from '@/db/schema' -import { implantSchema, updateImplantSchema } from '@/validators/implantsValidator' -import { eq } from 'drizzle-orm' - -export default class Implant { - static async insert(req: Request, res: Response) { - try { - // Validação dos dados com Zod - const validation = implantSchema.safeParse(req.body) - if (!validation.success) { - return res.status(400).json({ error: validation.error.format() }) - } - - const { name, price, cyberCost, bodyPart } = validation.data - - // Inserir no banco de dados - const result = await db - .insert(implantsTable) - .values({ - name, - price, - cyberCost, - bodyPart, - }) - .returning() - - res.status(201).json({ - message: 'Implante criado com sucesso', - implant: result, - }) - } catch (error) { - console.error(error) - res.status(500).json({ error: 'Erro ao criar implante' }) - } - } - - static async get(req: Request, res: Response) { - try { - const { id } = req.params - - const implantId = parseInt(id, 10) - - // Verificar se a conversão foi bem-sucedida - if (isNaN(implantId)) { - return res.status(400).json({ error: 'ID inválido' }) - } - - // Buscar o implante no banco de dados - const implant = await db.query.implantsTable.findFirst({ - where: eq(implantsTable.id, implantId), - }) - - // Verificar se o implante existe - if (!implant) { - return res.status(404).json({ error: 'Implante não encontrado' }) - } - - // Retornar o implante encontrado - res.status(200).json({ implant }) - } catch (error) { - console.error(error) - res.status(500).json({ error: 'Erro ao buscar implante' }) - } - } - - static async update(req: Request, res: Response) { - try { - const { id } = req.params - const updateData = req.body - - const implantId = parseInt(id, 10) - - if (isNaN(implantId)) { - return res.status(400).json({ error: 'ID inválido' }) - } - - // Validação dos dados com Zod - const validation = updateImplantSchema.safeParse(updateData) - if (!validation.success) { - return res.status(400).json({ error: validation.error.format() }) - } - - // Verificar se o implante existe - const implant = await db.query.implantsTable.findFirst({ - where: eq(implantsTable.id, implantId), - }) - - if (!implant) { - return res.status(404).json({ error: 'Implante não encontrado' }) - } - - // Preparar os dados para atualização - const dataToUpdate = { - name: updateData.name || implant.name, // Atualiza o nome se fornecido, senão mantém o atual - price: updateData.price || implant.price, // Atualiza o preço se fornecido, senão mantém o atual - cyberCost: updateData.cyberCost || implant.cyberCost, // Atualiza o custo de cyberpsychosis se fornecido, senão mantém o atual - bodyPart: updateData.bodyPart || implant.bodyPart, // Atualiza a parte do corpo se fornecido, senão mantém o atual - } - - // Atualizar o implante no banco de dados - const updatedImplant = await db - .update(implantsTable) - .set(dataToUpdate) - .where(eq(implantsTable.id, implantId)) - .returning() // Retorna o implante atualizado - - // Retornar o implante atualizado - res.status(200).json({ implant: updatedImplant }) - } catch (error) { - console.error(error) - res.status(500).json({ error: 'Erro ao atualizar implante' }) - } - } - - static async delete(req: Request, res: Response) { - try { - const { id } = req.params - - const implantId = parseInt(id, 10) - - if (isNaN(implantId)) { - return res.status(400).json({ error: 'ID inválido' }) - } - - // Verificar se o implante existe - const implant = await db.query.implantsTable.findFirst({ - where: eq(implantsTable.id, implantId), - }) - - if (!implant) { - return res.status(404).json({ error: 'Implante não encontrado' }) - } - - // Deletar o implante no banco de dados - await db.delete(implantsTable).where(eq(implantsTable.id, implantId)) - - // Retornar confirmação de deleção - res.status(200).json({ message: 'Implante deletado com sucesso' }) - } catch (error) { - console.error(error) - res.status(500).json({ error: 'Erro ao deletar implante' }) - } - } - - static async buy(req: Request, res: Response) { - try { - const { user_id, implant_id } = req.body - - // Verificar se o usuário existe - const user = await db.query.userTable.findFirst({ - where: eq(userTable.id, user_id), - }) - - if (!user) { - return res.status(404).json({ error: 'Usuário não encontrado' }) - } - - // Verificar se o implante existe - const implant = await db.query.implantsTable.findFirst({ - where: eq(implantsTable.id, implant_id), - }) - - if (!implant) { - return res.status(404).json({ error: 'Implante não encontrado' }) - } - - // Converter os valores para números - const userMoney = parseFloat(user.money) - const implantPrice = parseFloat(implant.price) - const userCyberpsychosis = parseInt(user.cyberpsychosis, 10) - const implantCybercost = parseInt(implant.cyberCost, 10) - const userCyberLimit = parseInt(user.cyberLimit, 10) - - // Verificar se o usuário tem saldo suficiente - if (userMoney < implantPrice) { - return res.status(400).json({ error: 'Saldo insuficiente' }) - } - - // Calcular o novo saldo - const newMoney = userMoney - implantPrice - const newCyberpsychosis = userCyberpsychosis + implantCybercost - - if (newCyberpsychosis >= userCyberLimit) { - return res.status(400).json({ error: 'Você irá se transformar em um cyberpsycho!' }) - } - - const updatedUser = await db - .update(userTable) - .set({ - money: newMoney.toString(), - cyberpsychosis: newCyberpsychosis.toString(), - }) - .where(eq(userTable.id, user_id)) - .returning() - - // Registrar a compra - const purchase = await db - .insert(purchases) - .values({ - user_id, - implant_id, - }) - .returning() - - // Retornar a compra realizada - res.status(201).json({ - message: 'Compra realizada com sucesso', - purchase, - user: updatedUser, - }) - } catch (error) { - console.error(error) - res.status(500).json({ error: 'Erro ao realizar compra' }) - } - } -} diff --git a/src/handlers/user.ts b/src/handlers/user.ts index faee41d..e69de29 100644 --- a/src/handlers/user.ts +++ b/src/handlers/user.ts @@ -1,206 +0,0 @@ -import { type Request, type Response } from "express"; -import { db } from "@/db"; -import { userTable } from "@/db/schema"; -import { userSchema, updateUserSchema } from "@/validators/userValidator"; -import { eq } from "drizzle-orm"; -import bcrypt from "bcrypt"; -import jwt from "jsonwebtoken"; - -export default class User { - - static async insert(req: Request, res: Response) { - try { - // Validação dos dados com Zod - const validation = userSchema.safeParse(req.body); - if (!validation.success) { - return res.status(400).json({ error: validation.error.format() }); - } - - const { name, password, email, birthday, cpf, money, cyberpsychosis, cyberLimit } = validation.data; - - // Hashear a senha - const saltRounds = 12; // Número de rounds para o salt (recomendado: 12) - const hashedPassword = await bcrypt.hash(password, saltRounds); - - // Inserir no banco de dados - const result = await db.insert(userTable).values({ - name, - password: hashedPassword, // Usar a senha hasheada - email, - birthday, - cpf, - money, - cyberpsychosis: cyberpsychosis || null, - cyberLimit: cyberLimit || null - }).returning(); - - res.status(201).json({ message: "Usuário criado com sucesso", user: result }); - } catch (error) { - console.error(error); - res.status(500).json({ error: "Erro ao criar usuário" }); - } - } - - static async get(req: Request, res: Response) { - try { - const { id } = req.params; // Pegando o id passado por params - - // Converter o id para número - const userId = parseInt(id, 10); - - // Verificar se a conversão foi bem-sucedida - if (isNaN(userId)) { - return res.status(400).json({ error: "ID inválido" }); - } - - // Buscar o usuário no banco de dados - const user = await db.query.userTable - .findFirst({ - where: eq(userTable.id, id), // Ele vai reclamar que o tipo do id de req.params não é type UserModel['id'], pode ignorar - }) - - // Verificar se o usuário existe - if (!user) { - return res.status(404).json({ error: "Usuário não encontrado" }); - } - - // Retornar o usuário encontrado - res.status(200).json({ user }); - } catch (error) { - console.error(error); - res.status(500).json({ error: "Erro ao buscar usuário" }); - } - } - - static async update(req: Request, res: Response) { - try { - const { id } = req.params; - const updateData = req.body; // Pegando os dados para atualização - - // Converter o id para número - const userId = parseInt(id, 10); - - if (isNaN(userId)) { - return res.status(400).json({ error: "ID inválido" }); - } - - // Validação dos dados com Zod - const validation = updateUserSchema.safeParse(req.body); - if (!validation.success) { - return res.status(400).json({ error: validation.error.format() }); - } - - // Verificar se o usuário existe - const user = await db.query.userTable - .findFirst({ - where: eq(userTable.id, userId), - }); - - if (!user) { - return res.status(404).json({ error: "Usuário não encontrado" }); - } - - // Preparar os dados para atualização - const dataToUpdate = { - name: updateData.name || user.name, // Atualiza o nome se fornecido, senão mantém o atual - password: updateData.password || user.password, // Atualiza a senha se fornecido, senão mantém a atual - email: updateData.email || user.email, // Atualiza o email se fornecido, senão mantém o atual - birthday: updateData.birthday || user.birthday, // Atualiza o aniversário se fornecido, senão mantém o atual - cpf: updateData.cpf || user.cpf, // Atualiza o CPF se fornecido, senão mantém o atual - money: updateData.money || user.money, // Atualiza o dinheiro se fornecido, senão mantém o atual - cyberpsychosis: updateData.cyberpsychosis || user.cyberpsychosis, // Atualiza o nível de cyberpsychosis se fornecido, senão mantém o atual - cyberLimit: updateData.cyberLimit || user.cyberLimit // Atualiza o cyberLimit se fornecido, senão mantém o atual - }; - - // Atualizar o usuário no banco de dados - const updatedUser = await db.update(userTable) - .set(dataToUpdate) - .where(eq(userTable.id, userId)) - .returning(); // Retorna o usuário atualizado - - // Retornar o usuário atualizado - res.status(200).json({ user: updatedUser }); - } catch (error) { - console.error(error); - res.status(500).json({ error: "Erro ao atualizar usuário" }); - } - } - - static async delete (req: Request, res: Response) { - try { - const { id } = req.params; - - const userId = parseInt(id, 10); - if (isNaN(userId)) { - return res.status(400).json({ error: "ID inválido" }); - } - - // Verificar se o usuário existe - const user = await db.query.userTable - .findFirst({ - where: eq(userTable.id, userId), - }); - - if (!user) { - return res.status(404).json({ error: "Usuário não encontrado" }); - } - - // Deletar o usuário no banco de dados - await db.delete(userTable) - .where(eq(userTable.id, userId)); - - // Retornar confirmação de deleção - res.status(200).json({ message: "Usuário deletado com sucesso" }); - } catch (error) { - console.error(error); - res.status(500).json({ error: "Erro ao deletar usuário" }); - } - } - - static async login(req: Request, res: Response) { - try { - const { email, password } = req.body; - - // Verificar se o email e a senha foram fornecidos - if (!email || !password) { - return res.status(400).json({ error: "Email e senha são obrigatórios" }); - } - - // Buscar o usuário no banco de dados pelo email - const user = await db.query.userTable - .findFirst({ - where: eq(userTable.email, email), - }); - - // Verificar se o usuário existe - if (!user) { - return res.status(401).json({ error: "Credenciais inválidas" }); - } - - // Verificar se a senha está correta - const isPasswordValid = await bcrypt.compare(password, user.password); - if (!isPasswordValid) { - return res.status(401).json({ error: "Credenciais inválidas" }); - } - - // Gerar o token JWT - const jwtSecret = process.env["APP_SECRET"]; // Chave secreta para assinar o token - if (!jwtSecret) { - throw new Error("Chave JWT_SECRET não configurada"); - } - - const token = jwt.sign( - { id: user.id, email: user.email }, // Dados do usuário a serem incluídos no token - jwtSecret, // Chave secreta - { expiresIn: "1h" } // Tempo de expiração do token (1 hora) - ); - - // Retornar o token - res.status(200).json({ message: "Login bem-sucedido", token }); - } catch (error) { - console.error(error); - res.status(500).json({ error: "Erro ao realizar login" }); - } - } - -}; diff --git a/src/index.ts b/src/index.ts index 4ab0b09..7177704 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,19 +13,6 @@ const app = express() app.use(urlencoded({ extended: true })) app.use(json()) -// Rotas de usuário -app.post('/addUser', User.insert) -app.get('/getUser/:id', Auth, User.get) -app.put('/updateUser/:id', Auth, User.update) -app.delete('/deleteUser/:id', Auth, User.delete) -app.post('/login', User.login) - -// Rotas de implantes -app.post('/addImplant', Auth, Implant.insert) -app.get('/getImplant/:id', Implant.get) -app.put('/updateImplant/:id', Auth, Implant.update) -app.delete('/deleteImplant/:id', Auth, Implant.delete) -app.post('/purchase', Auth, Implant.buy) // Definir a porta e iniciar o servidor const PORT = process.env['PORT'] || 3000 diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts index 9e94012..e69de29 100644 --- a/src/middleware/auth.ts +++ b/src/middleware/auth.ts @@ -1,31 +0,0 @@ -import { type Request, type Response, type NextFunction } from "express"; -import jwt, { type JwtPayload } from "jsonwebtoken"; - -declare global { - namespace Express { - interface Request { - user?: JwtPayload | string; // Adiciona a propriedade 'user' ao tipo Request - } - } -} - -export const Auth = (req: Request, res: Response, next: NextFunction) => { - const token = req.header("Authorization")?.replace("Bearer ", ""); - - if (!token) { - return res.status(401).json({ error: "Token de autenticação não fornecido" }); - } - - const jwtSecret = process.env["APP_SECRET"]; - if (!jwtSecret) { - throw new Error("Chave JWT_SECRET não configurada"); - } - - try { - const decoded = jwt.verify(token, jwtSecret); // Verifica o token - req.user = decoded; // Adiciona os dados do usuário à requisição - next(); // Passa para o próximo middleware ou rota - } catch (error) { - res.status(401).json({ error: "Token inválido ou expirado" }); - } -}; \ No newline at end of file diff --git a/src/validators/implantsValidator.ts b/src/validators/implantsValidator.ts index 3611345..e69de29 100644 --- a/src/validators/implantsValidator.ts +++ b/src/validators/implantsValidator.ts @@ -1,28 +0,0 @@ -import { z } from "zod"; - -// Lista de valores permitidos para bodyPart -const bodyPartsEnum = [ - "FrontalCortex", - "OperatingSystem", - "Arms", - "Skeleton", - "NervousSystem", - "IntegumentarySystem", - "Face", - "Hands", - "CirculatorySystem", - "Legs", -] as const; - -// Esquema de validação para implantes -export const implantSchema = z.object({ - name: z.string().min(1, "O nome é obrigatório").max(255, "O nome deve ter no máximo 255 caracteres"), - price: z.string().regex(/^\d+(\.\d{1,2})?$/, "O preço deve ser um número decimal"), - cyberCost: z.string().regex(/^\d+(\.\d{1,2})?$/, "O custo de cyberpsychosis deve ser um número inteiro positivo").default("5"), - bodyPart: z.enum(bodyPartsEnum, { - message: "A parte do corpo fornecida é inválida", - }), -}); - -// Esquema de validação para atualização de implantes (todos os campos opcionais) -export const updateImplantSchema = implantSchema.partial(); \ No newline at end of file diff --git a/src/validators/userValidator.ts b/src/validators/userValidator.ts index c91be46..e69de29 100644 --- a/src/validators/userValidator.ts +++ b/src/validators/userValidator.ts @@ -1,25 +0,0 @@ -import { z } from 'zod' - -// Esquema de validação para o usuário -export const userSchema = z.object({ - name: z.string().min(3, 'O nome deve ter pelo menos 3 caracteres'), - password: z.string().min(6, 'A senha deve ter pelo menos 6 caracteres'), - email: z.string().email('E-mail inválido'), - birthday: z.string().refine((date) => !isNaN(Date.parse(date)), 'Data de nascimento inválida'), - cpf: z.string().length(11, 'CPF deve ter exatamente 11 dígitos').regex(/^\d+$/, 'CPF deve conter apenas números'), - money: z - .string() - .regex(/^\d+(\.\d{1,2})?$/, 'Valor inválido') - .default('0'), - cyberpsychosis: z - .string() - .regex(/^\d+(\.\d{1,2})?$/, 'Valor inválido') - .optional(), - cyberLimit: z - .string() - .regex(/^\d+(\.\d{1,2})?$/, 'Valor inválido') - .optional(), -}) - -// Esquema de validação para atualização (todos os campos opcionais) -export const updateUserSchema = userSchema.partial() -- GitLab