Skip to content

Igordevz/Giftly

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Event's API Documentation

This document provides a comprehensive guide to the Event's API, detailing its functionalities, endpoints, and how to interact with them. It's designed for both AI consumption and frontend integration.

🚀 Getting Started

Prerequisites

Before running the API, ensure you have the following installed:

  • Node.js (v18 or higher)
  • npm (as your package manager)
  • MySQL Database

Environment Variables

Create a .env file in the project root with the following variables:

DATABASE_URL="mysql://user:password@host:port/database"
JWT_SECRET="your_jwt_secret_key"
R2_ENDPOINT="https://<your_account_id>.r2.cloudflarestorage.com"
R2_ACCESS_KEY_ID="your_r2_access_key_id"
R2_SECRET_ACCESS_KEY="your_r2_secret_access_key"
R2_BUCKET_NAME="your_r2_bucket_name"

Database Setup

This API uses Prisma for database management.

  1. Install Dependencies:
    npm install
  2. Apply Migrations: After setting up your DATABASE_URL in .env, apply the database schema changes:
    npx prisma migrate dev --name initial_setup # Or the latest migration name
    If you've made changes to prisma/schema.prisma (e.g., adding enums), ensure you run npx prisma migrate dev to update your database.

Running the API

npm run dev

The API will typically run on http://localhost:3000.

🛡️ Authentication & Authorization

This API uses JWT (JSON Web Tokens) for authentication.

  • Authentication: After successful login (POST /user/login), you will receive a JWT.

  • Authorization: For protected routes, include the JWT in the jwt header of your requests.

    jwt: YOUR_JWT_TOKEN_HERE
    

Middlewares

  • validateEventUser: Ensures the authenticated user is the host of the event specified in the URL parameters.
  • validateGuestAccess: Ensures the authenticated user is a guest of the event specified in the URL parameters.

🗺️ API Endpoints

User Management

1. Register User

  • Route: POST /user/register
  • Controller: CreateUser (src/controllers/user/create-user.ts)
  • Description: Registers a new user in the system.
  • Request Body Example:
    {
      "cpf": "12345678901",
      "name": "Fulano de Tal",
      "phone": "11987654321",
      "password": "securepassword123",
      "email": "fulano@example.com"
    }
  • Expected Response (201 Created):
    {
      "success": true,
      "message": "Usuário criado com sucesso!",
      "jwt": "YOUR_NEWLY_GENERATED_JWT"
    }

2. Validate JWT

  • Route: GET /user
  • Controller: ValidateJwt (src/controllers/user/validate-jwt.ts)
  • Description: Validates the provided JWT and returns user information.
  • Headers: jwt: YOUR_JWT_TOKEN
  • Expected Response (200 OK):
    {
      "success": true,
      "message": "Token validado!",
      "user": {
        "id": 2,
        "cpf": "89069633515",
        "name": "Julia Santos",
        // ... other user details and relations
      }
    }

3. User Login

  • Route: POST /user/login
  • Controller: Login (src/controllers/user/login.ts)
  • Description: Authenticates a user and returns a JWT.
  • Headers: (None required, but Content-Type: application/json)
  • Request Body Example:
    {
      "cpf": "12345678901",
      "password": "securepassword123"
    }
  • **Expected Response (200 OK):n ```json { "success": true, "message": "Login realizado com sucesso!", "jwt": "YOUR_GENERATED_JWT" }
    
    

Event Management (Host Actions)

These routes require the jwt header of the event host.

1. Create Event

  • Route: POST /event/create
  • Controller: CreateEvent (src/controllers/event/create-event.ts)
  • Description: Creates a new event.
  • Headers: jwt: HOST_JWT_TOKEN
  • Request Body Example:
    {
      "title": "Minha Festa de Aniversário",
      "date": "2025-12-25T20:00:00Z",
      "location": "Salão de Festas do Condomínio"
    }
  • Expected Response (201 Created):
    {
      "success": true,
      "message": "Evento criado com sucesso!",
      "event": {
        "id": 1,
        "title": "Minha Festa de Aniversário",
        // ... other event details
      }
    }

2. Update Event Details

  • Route: PATCH /events/:eventId
  • Controller: updateEventDetails (src/controllers/event/update-event-details.ts)
  • Middleware: validateEventUser
  • Description: Updates details of an existing event. Supports partial updates.
  • Headers: jwt: HOST_JWT_TOKEN
  • Request Body Example (partial update):
    {
      "title": "Minha Super Festa de Aniversário",
      "location": "Novo Salão de Festas"
    }
  • Expected Response (200 OK):
    {
      "message": "Detalhes do evento atualizados com sucesso!",
      "event": {
        "id": 1,
        "title": "Minha Super Festa de Aniversário",
        // ... updated event details
      }
    }

3. Invite Guest to Event

  • Route: POST /events/:eventId/invite
  • Controller: inviteGuest (src/controllers/event/invite-guest.ts)
  • Middleware: validateEventUser
  • Description: Invites a user (identified by CPF) to an event.
  • Headers: jwt: HOST_JWT_TOKEN
  • Request Body Example:
    {
      "cpf": "11122233344"
    }
  • **Expected Response (200 OK):n ```json { "message": "Convidado adicionado com sucesso ao evento." }
    
    

4. Remove Guest from Event

  • Route: DELETE /events/:eventId/guests/:guestUserId
  • Controller: removeGuest (src/controllers/event/remove-guest.ts)
  • Middleware: validateEventUser
  • Description: Removes a guest from an event.
  • Headers: jwt: HOST_JWT_TOKEN
  • Expected Response (200 OK):
    {
      "message": "Convidado removido do evento com sucesso!"
    }

5. Delete Event

  • Route: DELETE /events/:eventId
  • Controller: deleteEvent (src/controllers/event/delete-event.ts)
  • Middleware: validateEventUser
  • Description: Deletes an event and all its associated gifts, chosen gifts, and guest relationships.
  • Headers: jwt: HOST_JWT_TOKEN
  • Expected Response (200 OK):
    {
      "message": "Evento e todos os dados relacionados removidos com sucesso!"
    }

Gift Management (Host Actions)

These routes require the jwt header of the event host.

1. Add Gift to Event

  • Route: POST /events/:eventId/gifts
  • Controller: updateGifts (src/controllers/event/update-gifts.ts)
  • Middleware: validateEventUser
  • Description: Adds a new gift to an event. Can create new categories/payment types if specified by name/type.
  • Headers: jwt: HOST_JWT_TOKEN
  • Request Body Example (new category by name, new payment by type):
    {
      "name": "Fone de Ouvido Bluetooth",
      "price": 150.75,
      "limit": 5,
      "category": {
        "name": "Eletrônicos"
      },
      "payment": {
        "type": "pix"
      },
      "image": {
        "contentType": "image/jpeg",
        "name": "fone-bluetooth.jpg"
      }
    }
  • Expected Response (201 Created):
    {
      "gift": {
        "id": 1,
        "name": "Fone de Ouvido Bluetooth",
        // ... other gift details
      },
      "uploadUrl": "https://your_r2_bucket_url/..."
    }
    Note: The uploadUrl is a pre-signed URL. Your frontend should use this URL to upload the actual image file via a PUT request.

2. Update Gift Details

  • Route: PATCH /events/:eventId/gifts/:giftId
  • Controller: updateGift (src/controllers/event/update-gift.ts)
  • Middleware: validateEventUser
  • Description: Updates details of an existing gift. Supports partial updates. Can create new categories/payment types if specified by name/type.
  • Headers: jwt: HOST_JWT_TOKEN
  • Request Body Example (partial update, new category by name):
    {
      "name": "Fone de Ouvido Premium",
      "price": 250.00,
      "category": {
        "name": "Tecnologia"
      }
    }
  • Expected Response (200 OK):
    {
      "message": "Presente atualizado com sucesso!",
      "gift": {
        "id": 1,
        "name": "Fone de Ouvido Premium",
        // ... updated gift details
      },
      "uploadUrl": "https://your_r2_bucket_url/..." // Only if image was updated
    }

3. Delete Gift

  • Route: DELETE /events/:eventId/gifts/:giftId
  • Controller: deleteGift (src/controllers/event/delete-gift.ts)
  • Middleware: validateEventUser
  • Description: Deletes a gift and all its associated chosen gifts.
  • Headers: jwt: HOST_JWT_TOKEN
  • Expected Response (200 OK):
    {
      "message": "Presente removido com sucesso!"
    }

Gift Selection & Payment (Guest Actions)

These routes require the jwt header of an event guest.

1. Choose a Gift

  • Route: POST /events/:eventId/gifts/:giftId/choose
  • Controller: chooseGift (src/controllers/event/choose-gift.ts)
  • Middleware: validateGuestAccess
  • Description: Allows an invited guest to choose a gift for an event.
  • Headers: jwt: GUEST_JWT_TOKEN
  • Request Body Example (with message, new payment by type):
    {
      "message": "Parabéns pelo evento! Espero que goste do presente.",
      "payment": {
        "type": "pix"
      }
    }
  • Expected Response (201 Created):
    {
      "message": "Presente escolhido com sucesso!",
      "chosenGift": {
        "id": 1,
        "userId": 2,
        "giftId": 1,
        // ... other chosen gift details
      }
    }

2. Simulate Payment for Chosen Gift

  • Route: PATCH /events/:eventId/gifts/:giftId/chosen/:chosenGiftId/simulate-payment
  • Controller: simulatePayment (src/controllers/event/simulate-payment.ts)
  • Middleware: validateGuestAccess
  • Description: Simulates a payment for a chosen gift, updating its status to PAID.
  • Headers: jwt: GUEST_JWT_TOKEN
  • Request Body Example: (No body required for this endpoint)
    {}
  • Expected Response (200 OK):
    {
      "message": "Pagamento simulado com sucesso! Status atualizado para PAGO.",
      "chosenGift": {
        "id": 1,
        "status": "PAID",
        // ... other chosen gift details
      }
    }

⚠️ Error Handling

The API returns standard HTTP status codes and JSON error objects.

  • 400 Bad Request: Validation errors (e.g., invalid input format, missing required fields).
    {
      "message": "Erro de validação.",
      "errors": {
        "field_name": ["Error message for field"]
      }
    }
  • 401 Unauthorized: Missing or invalid JWT.
  • 403 Forbidden: Authenticated user does not have permission to access the resource (e.g., guest trying to manage event, non-host trying to update event).
  • 404 Not Found: Resource not found (e.g., event, gift, user).
  • 409 Conflict: Resource conflict (e.g., user already invited, gift already chosen).
  • 500 Internal Server Error: Unexpected

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors